简体   繁体   English

PHP正则表达式查找并附加到字符串

[英]PHP regular expression find and append to string

I'm trying to use regular expressions (preg_match and preg_replace) to do the following:我正在尝试使用正则表达式(preg_match 和 preg_replace)来执行以下操作:

Find a string like this:找到这样的字符串:

{%title=append me to the title%}

Then extract out the title part and the append me to the title part.然后提取title部分append me to the title部分。 Which I can then use to perform a str_replace(), etc.然后我可以用它来执行 str_replace() 等。

Given that I'm terrible at regular expressions, my code is failing...鉴于我在正则表达式方面很糟糕,我的代码失败了......

 preg_match('/\{\%title\=(\w+.)\%\}/', $string, $matches);

What pattern do I need?我需要什么模式? :/ :/

I think it's because the \\w operator doesn't match spaces.我认为这是因为\\w运算符不匹配空格。 Because everything after the equal sign is required to fit in before your closing % , it all has to match whatever is inside those brackets (or else the entire expression fails to match).因为等号之后的所有内容都需要在关闭%之前适合,所以它必须与括号内的内容匹配(否则整个表达式无法匹配)。

This bit of code worked for me:这段代码对我有用:

$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 ) 

Note that the use of the + (one or more) means that an empty expression, ie.请注意,使用+ (一个或多个)表示空表达式,即。 {%title=%} won't match. {%title=%}不匹配。 Depending on what you expect for white space, you might want to use the \\s after the \\w character class instead of an actual space character.根据您对空白的期望,您可能希望在\\w字符类之后使用\\s而不是实际的空格字符。 \\s will match tabs, newlines, etc. \\s将匹配制表符、换行符等。

You can try:你可以试试:

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

Output:输出:

string(17) "{%TITLE=IS GOOD%}"

Note:笔记:

In your regex: /\\{\\%title\\=(\\w+.)\\%\\}/在您的正则表达式中: /\\{\\%title\\=(\\w+.)\\%\\}/

  • There is no need to escape % as its not a meta char.没有必要转义%因为它不是元字符。
  • There is no need to escape { and } .没有必要逃避{} These are meta char but only when used as a quantifier in the form of {min,max} or {,max} or {min,} or {num} .这些是元字符,但仅当以{min,max}{,max}{min,}{num}的形式用作量词时。 So in your case they are treated literally.所以在你的情况下,他们是按字面处理的。

Try this:尝试这个:

preg_match('/(title)\=(.*?)([%}])/s', $string, $matches);

The match[1] has your title and match[2] has the other part. match[1] 有你的标题,match[2] 有另一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM