View Full Version : Regular expression help
The Dark One
13-Nov-2003, 20:31
I want to use a PHP regular expression to match the following
<P class="copy"> [some text] </P>
and replace with
blah.php?p=[some text]
The paragraph tags could be upper or lower case, and there could be any number of other tags or space in there so its not really wise to use string replace or modify the original string. For example, could have
< P align="middle" clASS = "copy" bgcolor="#123456"> [some text] </p>
Try this :o)
[code:1:2c14bc68cc]
echo preg_replace("/(<\s*P[^>]*>)([^<]*<\/P>)/i", "\${1}blah.php?p=\${2}", $string);
[/code:1:2c14bc68cc]
Replaces <P align="left" tag="12774" Moo!>Blah</P>
with <P align="left" tag="12774" Moo!>blah.php?p=Blah</P>
If that's not what you wanted.... (and you just wanted to eliminate the entire <P ... > </P> as well then...
[code:1:2c14bc68cc]
echo preg_replace("/(<\s*P[^>]*>)([^<]*)(<\/P>)/i", "blah.php?p=\${2}", $string);
[/code:1:2c14bc68cc]
should produce just blah.php?p=whatever
-Sparky
The Dark One
13-Nov-2003, 22:10
Cool, ta.
I hate regex!
Brain_Murders
14-Nov-2003, 10:22
If you want the paragraph tags to be upper or lower case, mod the above so that instead of P you have [pP].
Also I didn't allow for spaces in the </p> tag.
Best to figure it out yourself really - then you get exactly what you want :o)
I don't particularly like regexps either, but just find some help pages and put together what you want. Keep testing until it works as you want it to.
If you want spaces in the </p> tag shove in /s* wherever you want the possibility of a space.
-Sparky
This site will save you loads of time when testing, saves contantly uploading files etc.
http://samuelfullman.com/team/php/tools/regular_expression_tester_p2.php
vBulletin® v3.7.0 Release Candidate 3, Copyright ©2000-2009, Jelsoft Enterprises Ltd.