Forum Moderators: coopster

Message Too Old, No Replies

preg_replace question

having problem with a pattern

         

baze22

3:12 pm on Feb 17, 2005 (gmt 0)

10+ Year Member



This is probably simple, but I'm not seeing the problem. (I think my brain is regex resistant :)) Here's what I'm playing with:

$teststr = 'This is a {b}test {/b} of {i}preg{/i} stuff'; // These {} should be brackets, forum software would strip them out otherwise.

echo preg_replace('(\[.*\])', "", $teststr);


( curly braces {} above should be changed to brackets [], forum software would strip them out otherwise.)

I just want the '[whatever]', whatever is in brackets to go away. Here's what I get running the above:

This is a stuff

I thought I was matching a [ then 0 or more characters then a closing ]. Obviously I'm missing something. Appreciate any assistance.

baze

mattx17

3:52 pm on Feb 17, 2005 (gmt 0)

10+ Year Member



Try using it like this:

echo preg_replace('/\[\/?.*?\]/', "", $teststr);

The .*? means 'non-greedy', which means it will stop at the next end bracket. If you do just .*, it will go all the way until the last end bracket in the entire string, which woudn't be good if you had more than one bracket enclosed item. Adding \/? in there also makes it so it will get rid of the closing tags.

coopster

6:39 pm on Feb 17, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, mattx17.

Another option would be to simply add the Ungreedy [php.net] modifier

echo preg_replace('(\[.*\])Us', "", $teststr);
I threw in the "s" modifier too, in case the pattern ever broke over a newline.

baze22

7:47 pm on Feb 17, 2005 (gmt 0)

10+ Year Member



I appreciate the help. That took care of it. I have some projects in mind that will most likely require that I get a little more familiar with regex, so I'll probabaly be back with more questions in the future.

Thanks again,

baze