[英]PHP regular expression find and append to string
我正在尝试使用正则表达式(preg_match 和 preg_replace)来执行以下操作:
找到这样的字符串:
{%title=append me to the title%}
然后提取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,}
或{num}
的形式用作量词时。 所以在你的情况下,他们是按字面处理的。尝试这个:
preg_match('/(title)\=(.*?)([%}])/s', $string, $matches);
match[1] 有你的标题,match[2] 有另一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.