收录日期:2021/01/23 18:37:22 时间:2010-03-31 05:01:25 标签:php,regex,string

I'm trying to use regular expressions (preg_match and preg_replace) to do the following:

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. Which I can then use to perform a str_replace(), etc.

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. 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. 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. \s will match tabs, newlines, etc.

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+.)\%\}/

  • 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}. So in your case they are treated literally.

Try this:

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

The match[1] has yout title and match[2] has the other part.