【问题标题】:changing url pattern using regular expression in php在 php 中使用正则表达式更改 url 模式
【发布时间】:2013-06-27 02:48:15
【问题描述】:

我想我是 PHP 的菜鸟。

我正在尝试将 url 模式更改为另一种模式

来自

http://da.feedsportal.com/c/34762/f/640634/s/2dd0817c/l/0L0Sexample0Bco0Bkr0Carti0Cpolitics0Cassembly0C5933970Bhtml/ia1.htm

http://www.example.co.kr/arti/politics/assembly/593397.html

所以我只从原始网址中获取“example0Bco0Bkr0Carti0Cpolitics0Cassembly0C5933970Bhtml”并稍微调整一下“0B”->“。”和 '0C' -> '/'

应删除 da.feedsportal.com/c/34762/f/640634/s/2dd0817c/l/0L0S 和 /ia1.htm 等其他部分。

任何帮助将不胜感激。

【问题讨论】:

  • 问题是 URL 的模式是什么?
  • @SH 没错。我将用 'code'(preg_replace($patterns,$replacements,$urls);) 替换它
  • @SH $pattern 应该是原始 url 的模式,而 $replacement 应该是预期的 url 模式。

标签: php regex url


【解决方案1】:

只需使用urlencode

echo urlencode("http://www.example.co.kr/arti/politics/assembly/593397.html");
//=> http%3A%2F%2Fwww.example.co.kr%2Farti%2Fpolitics%2Fassembly%2F593397.html

那你就不用自己写了

【讨论】:

  • 嗯....我需要获取一个模式并使用 preg_replace 更改它。请参阅对问题的评论并帮助我。 :)
  • 我在帮你。无论您在上面的代码中做什么都是……错误的。如果您正确编码 url 数据,您将不必实现自己的疯狂脆弱的正则表达式解决方案。
  • stackoverflow.com/questions/16746230/… 这是我的问题的历史。 :) 我正在将一种模式替换为另一种模式,因为我从提要中获得的 url 模式并没有真正将用户链接到正确的位置。 :)
【解决方案2】:

使用 strposstrrpossubstrstr_replace。我们将分4个主要步骤进行。查找子字符串的开始和结束。一点验证。获取子字符串。转换子串。

基本上:

function convert ($inputString) {
    $start = strpos( $inputString, '0L0S' );
    $end = strrpos( $inputString, '/' );

    if(! $start){
        return false;
    }

    $start = $start + 4; // this is because strpos gives start of found string
    $length = $end - $start;
    $innerString = substr( $inputString, $start, $length);

    $pass1 = str_replace ('0B', '.', $innerString);
    $pass2 = str_replace ('0C', '/', $pass1);

    return $pass2;
}

我敢肯定有一种奇特的方法可以做到这一点。但这应该可行。

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多