在php中查找具有特定字符串模式的子字符串

时间:2017-02-15 09:45:32

标签: php regex substring

我想在 ___ string_string ___ 模式的字符串中找到子字符串,其中string_string可以是任何字符串。

$string = "This string contains ___MY_VALUE___ which I want to replace and there is also ___ONE_MORE_VALUE___ which I want to replace";`

4 个答案:

答案 0 :(得分:1)

如果您只想要一个字符串&在___之间,然后是

之间的下划线,而不是其他内容
/___([a-zA-Z_]*)___/m

Here's the working example

修改

为了解决______上的误报,我添加了一个积极的预测,并进行了其他一些调整。

/_{3}(?=.*[a-zA-Z_])(.*[a-zA-Z_])_{3}/m

_{3} - 匹配3下划线

(?=.*[a-zA-Z_]) - 确保其中一个字符存在的正面预测

(.*[a-zA-Z_]) - 实际匹配组

_{3} - 并匹配结尾的3个下划线

Here's a working example of this second version

答案 1 :(得分:1)

使用preg_replace_callback()

尝试此操作
$string = "This string contains ___MY_VALUE___ which I want to replace and there is also ___ONE_MORE_VALUE___ which I want to replace";

$replaced = preg_replace_callback("/\___([a-zA-Z_]*)\___/", function($m){
    return "(replaced {$m[1]})";
}, $string);


print_r($replaced);

答案 2 :(得分:1)

使用具有特定正则表达式模式的preg_replace_callback的解决方案:

// custom replacement list
$pairs = ['___MY_VALUE___' => 123, '___ONE_MORE_VALUE___' => 456];
$str = '"This string contains ___MY_VALUE___ which I want to replace and there is also ___ONE_MORE_VALUE___ which I want to replace";';

$str = preg_replace_callback('/___(([a-z]+_?)+)___/mi', function($m) use($pairs){
    return (isset($pairs[$m[0]]))? $pairs[$m[0]] : $m[0];
}, $str);

print_r($str);

输出:

"This string contains 123 which I want to replace and there is also 456 which I want to replace";

答案 3 :(得分:0)

要替换两个" 3下划线"之间不是3个下划线的所有内容,请使用此正则表达式:

/___((?:(?!___).)+)___/

替换"关键字"使用相应的值,使用preg_replace_callback,如:

$replace = array(
'MY_VALUE' => '**Replacement of MY_VALUE**',
'ONE_MORE_VALUE' => '**Replacement of ONE_MORE_VALUE**',
' third value to be replaced ' => '**Replacement of  third value to be replaced**',
);

$string = "This string contains ___MY_VALUE___ which I want to replace 
    and there is also ___ONE_MORE_VALUE___ which I want to replace. 
    This is the ___ third value to be replaced ___";

$string = preg_replace_callback('/___((?:(?!___).)+)___/', 
            function ($m) use($replace){
                return $replace[$m[1]];
            }
            , $string);
echo $string,"\n";

<强>输出:

This string contains **Replacement of MY_VALUE** which I want to replace 
and there is also **Replacement of ONE_MORE_VALUE** which I want to replace. 
This is the **Replacement of  third value to be replaced**