正则表达式没有按预期工作 - PHP preg_match_all

时间:2016-09-14 04:42:01

标签: php regex

我有一个字符串,其中包含花括号中的变量,我想用一个值替换它们。

$text = 'Hi My Name is ##{Name}## and I am ##{Adjective}##';

preg_match_all('/{([^#]+)}/i', $text, $matches);
foreach ($matches[1] as $key => $value) {
    $text = str_replace('{' . $value . '}', 'SomeValue', $text);
}
print_r($matches[1]);
print_r(str_replace('##', '', $text));

输出

Array ( [0] => Name [1] => Adjective ) 
Hi My Name is SomeValue and I am SomeValue

但是我无法处理字符串的不同变化。

1. $text = 'Hi My Name is ##{Name}{Adjective}##'
2. $text = 'Hi My Name is ##{Name}and I am{Adjective}##'
3. $text = 'Hi My Name is ##{Name}, {Adjective}##'
4. $text = 'Hi My Name is ##{Name} {Adjective}##'

我希望在数组输出中得到类似的结果,以便可以替换值

 Array ( [0] => Name [1] => Adjective ) 

注意:我能够确保' ##'将始终存在于花括号的开始和结束处,但不一定存在于花括号之间,例如示例字符串中的1,2,3,4点。

2 个答案:

答案 0 :(得分:2)

我建议将preg_replace_callback与模式/\{(.+?)}/一起使用,并使用这样的回调

$callback = function($matches) use (&$found) {
  $found[] = $matches[1];
  return 'SomeValue';
};

这会让您在$found数组中记录匹配,同时将整个{Name}{Adjective}替换为“SomeValue”。

$found = [];
$newTxt = str_replace('##', '',
    preg_replace_callback('/\{(.+?)}/', $callback, $txt));

在这里演示〜https://eval.in/641827

答案 1 :(得分:1)

根据您的问题,您可以先提取## ##之间的所有内容,解析它,然后再替换它。

$text1 = 'Hi My Name is ##{Name}{Adjective}##';
$text2 = 'Hi My Name is ##{Name}and I am{Adjective}##';
$text3 = 'Hi My Name is ##{Name}, {Adjective}##';
$text4 = 'Hi My Name is ##{Name} {Adjective}##';

$the_text = $text2;

#get the stuff that's between ## ## 
preg_match_all("/##.*?##/", $the_text, $matches);

foreach ($matches[0] as $match)
{
    # you will have to change this a bit as you have name and adjectives
    # but what this does is replace all the '{}' with 'somevalue'
    $replace_this = preg_replace("/\{.*?\}/", "somevalue", $match);
    # replaces the original matched part with the replaced part (into the original text)
    $the_text = str_replace($match, $replace_this, $the_text);
}
echo $the_text . "<br>";