PHP正则表达式查找并附加到字符串
我尝试使用正则表达式(preg_match和preg_replace)执行以下操作: 查找如下所示的字符串:PHP正则表达式查找并附加到字符串,php,regex,string,Php,Regex,String,我尝试使用正则表达式(preg_match和preg_replace)执行以下操作: 查找如下所示的字符串: {%title=append me to the title%} 然后提取出标题部分,并将附加到标题部分。然后我可以用它来执行str_replace()等 鉴于我在正则表达式方面很糟糕,我的代码失败了 preg_match('/\{\%title\=(\w+.)\%\}/', $string, $matches); 我需要什么样的图案/ 我认为这是因为\w运算符与空格不匹配。因为等
{%title=append me to the title%}
然后提取出标题
部分,并将附加到标题
部分。然后我可以用它来执行str_replace()等
鉴于我在正则表达式方面很糟糕,我的代码失败了
preg_match('/\{\%title\=(\w+.)\%\}/', $string, $matches);
我需要什么样的图案/ 我认为这是因为
\w
运算符与空格不匹配。因为等号后面的所有内容都需要在结束前放入%
,所以所有内容都必须匹配这些括号内的内容(否则整个表达式无法匹配)
这段代码对我很有用:
$str = '{%title=append me to the title%}';
preg_match('/{%title=([\w ]+)%}/', $str, $matches);
print_r($matches);
//gives:
//Array ([0] => {%title=append me to the title%} [1] => append me to the title )
请注意,使用+
(一个或多个)意味着空表达式,即{%title=%}
将不匹配。根据您对空格的期望,您可能希望在\w
字符类之后使用\s
,而不是实际的空格字符<代码>\s将匹配选项卡、换行符等。您可以尝试:
$str = '{%title=append me to the title%}';
// capture the thing between % and = as title
// and between = and % as the other part.
if(preg_match('#{%(\w+)\s*=\s*(.*?)%}#',$str,$matches)) {
$title = $matches[1]; // extract the title.
$append = $matches[2]; // extract the appending part.
}
// find these.
$find = array("/$append/","/$title/");
// replace the found things with these.
$replace = array('IS GOOD','TITLE');
// use preg_replace for replacement.
$str = preg_replace($find,$replace,$str);
var_dump($str);
输出:
string(17) "{%TITLE=IS GOOD%}"
注:
在正则表达式中:/\{\%title\=(\w+)\%\}/
- 无需将
转义为 不是元字符%
- 无需转义
和{
。 这些是元字符,但只有在 以…的形式用作量词}
或{min,max}
或{,max}
或{min,max}
。因此,在你的情况下,他们被逐字处理{num}
preg_match('/(title)\=(.*?)([%}])/s', $string, $matches);
比赛[1]有你的标题,比赛[2]有另一部分。@Gary:很高兴知道它能起作用。既然答案对你很有用,你可能想投一票。此外,如果这个答案是所有答案中最有用的,那么您可能希望通过勾选答案旁边的正确标记来接受它。干杯:)