Forum Moderators: coopster

Message Too Old, No Replies

preg replace using wildcards

what's the secret?

         

wesg

10:32 pm on Jul 30, 2008 (gmt 0)

10+ Year Member



I'm working on a WP plugin, and I want to use preg_replace to do the dirty work.

Unfortunately I'm having some trouble getting the expressions correct.

Say my test phrase is <em>Hello world</em> and I want to turn that into <strong>Hello world</strong>. My first expression was this

preg_replace('/\<em\>([^ ]+)\<\/em\>/', '<strong>$1</strong>', $test);

Naturally, this didn't work. I think my problem is the ([^ ]+) and $1 but I don't know how it's wrong. Any suggestions?

cameraman

11:42 pm on Jul 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try this for your pattern:
#<em>([^<]+)</em>#

wesg

9:16 pm on Jul 31, 2008 (gmt 0)

10+ Year Member



I was able to find the answer using another thread on this forum, but now I have another little issue.

The goal of my code is to be able to replace tags, while leaving the text inside alone. Currently if I have two identical pieces of code that I'm trying to replace, it only does half.

ie. <em>Hello world</em><em>Hello world</em>
should be
<strong>Hello world</strong><strong>Hello world</strong>
but instead it's
<strong>Hello world</em><em>Hello world</strong>

Any suggestions?

cameraman

9:21 pm on Jul 31, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try the pattern I posted; it's producing your 'should be' from your ie.

wesg

9:30 pm on Jul 31, 2008 (gmt 0)

10+ Year Member



Indeed you are right, cameraman.

Thanks!