tags:

views:

58

answers:

4

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? :/

A: 

I don't thing this would work

giga
Why won't it work...?
Gary
This is probably the least helpful answer I've ever seen on SO. If I hadn't also answered, I'd downvote it. :/
zombat
Maybe it was supposed to be a comment on someone else's answer.
Alan Moore
+1  A: 

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.

zombat
+1  A: 

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.
codaddict
That works great. Cheers
Gary
@Gary: Good to know it works. Since the answer was useful to you, you might wanna put an upvote. Also if this answer as the most helpful of all the answers you might wanna accept it by checking the right mark next to the answer. Cheers :)
codaddict
A: 

Try this:

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

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

pinaki