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

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

问题描述:

I want to find substring in a string with ___string_string___ pattern where string_string can be any string.

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

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

  $ string =“这个字符串包含我要替换的___MY_VALUE___,还有我要替换的___ONE_MORE_VALUE___”;`
  code>  pre  > 
  div>

The solution using preg_replace_callback with specific regex pattern:

// 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);

The output:

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

Provided you simply want a string & underscores, and nothing else, in between the ___'s, then;

/___([a-zA-Z_]*)___/m

Here's the working example

Edit

To fix the false positive on ______, I've added a positive lookahead, and made a couple of other tweaks.

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

_{3} - Matches 3 underscores

(?=.*[a-zA-Z_]) - Positive lookahead to make sure one of these characters is present

(.*[a-zA-Z_]) - The actual matching group

_{3} - And match the ending 3 underscores

Here's a working example of this second version

Try this using 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);

To replace everything that is not 3 underscores in between two "3 underscores", use this regex:

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

To replace "keywords" with corresponding values, use preg_replace_callback like that:

$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,"
";

Output:

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**