在某个字符/单词后替换字符但跳过第一个匹配并处理重复项

时间:2017-07-17 23:31:51

标签: php replace preg-replace str-replace preg-replace-callback

我必须替换URL中的字符,但只能形成某个点并处理重复的字符。

网址如下所示:

http://example.com/001-one-two.html#/param-what-ever
http://example.com/002-one-two-three.html#/param-what--ever-
http://example.com/003-one-two-four.html#/param2-what-ever-
http://example.com/004-one-two-five.html#/param33-what--ever---here-

他们应该是这样的:

http://example.com/001-one-two.html#/param-what_ever
http://example.com/002-one-two-three.html#/param-what_ever_
http://example.com/003-one-two-four.html#/param2-what_ever_
http://example.com/004-one-two-five.html#/param33-what_ever_here_

在单词中使用单个-字符替换_个字符(任意数字)但在-之后跳过第一个#/#/之后的字符串长度变化明显,我无法找到实现此目的的方法。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

以下是使用preg_replace_callback

的方法
$in = array(
'http://example.com/001-one-two.html#/param-what-ever',
'http://example.com/002-one-two-three.html#/param-what--ever-',
'http://example.com/003-one-two-four.html#/param2-what-ever-',
'http://example.com/004-one-two-five.html#/param33-what--ever---here-'
);

foreach($in as $str) {
    $res = preg_replace_callback('~^.*?#/[^-]+-(.+)$~', function ($m) {
                return preg_replace('/-+/', '_', $m[1]);
            },
            $str);
    echo "$res\n";
}

<强>解释

~           : regex delimiter
  ^         : start of string
    .*?     : 0 or more any character, not greedy
    #/      : literally #/
    [^-]+   : 1 or more any character that is not a dash
    -       : a dash
    \K      : forget all we have seen until here
    (.+)    : group 1, contains avery thing after the first dash after #/
  $         : end of string
~           : regex delimiter

<强>输出:

http://example.com/001-one-two.html#/param-what_ever
http://example.com/002-one-two-three.html#/param-what_ever_
http://example.com/003-one-two-four.html#/param2-what_ever_
http://example.com/004-one-two-five.html#/param33-what_ever_here_