Synook Posted July 20, 2007 Share Posted July 20, 2007 Hi all,I'm just wondering if anyone could help me work around nesting in a PCRE. For example, I have a string _This_ is a _short String_ Now, if I wanted it to find the phrases "This" and "short String", but not "This_ is a _short String" by using the _, how would I do it?Perhaps an example of this would be in WikiCode or similar, where "_This_ is a _short String_" would be parsed to "<u>This</u> is a <u>short string</u>" but not "<u>This<u> is a </u>short String</u>".Thanks Link to comment Share on other sites More sharing options...
jhecht Posted July 20, 2007 Share Posted July 20, 2007 I'm not exactly sure what you're asking, could you please give a few more details. From what i can tell you want to take _string_ and turn it into string and in that case i would say something like this would do: $regExp = array('/_(.*)_/i');$replaceWith = array('<u>\\1</u>');$string = "_This_ is a _short string_";$string = preg_replace($regExp,$replaceWith,$string); That should do the trick. Link to comment Share on other sites More sharing options...
Synook Posted July 20, 2007 Author Share Posted July 20, 2007 Hi Jhecht - yes you are right, that is what I want. However, if I do that then This_ is a _short String is produced, which I didn't want. So, how do I get it to produce This is a short String? Thanks Link to comment Share on other sites More sharing options...
jhecht Posted July 20, 2007 Share Posted July 20, 2007 $string = "_This_ is supposed to not be _underlined_, so uhm, yeah. what do you think about _that_<br />/hi/ *bob*"; $regEx = array("/_([a-z0-9]+\s?)_/i","/\/([a-z0-9]+\s?)\//i","/\*([a-z0-9]+\s?)\*/i"); $replace=array("<u>\\1</u>","<i>\\1</i>","<b>\\1</b>"); $string = preg_replace($regEx,$replace,$string); echo $string; That works fine for me, I also added things for bold and italics Link to comment Share on other sites More sharing options...
Synook Posted July 22, 2007 Author Share Posted July 22, 2007 Thanks :)Hmm... but what about something like "_This is underlined_ while this is not. _So is this_"? The script would only work for single words. This is the bit I couldn't get around Link to comment Share on other sites More sharing options...
jhecht Posted July 22, 2007 Share Posted July 22, 2007 $string = "_hey, you, yes, you._ supposed to be underlined.<br /> /This is supposed to be/ *bold*<br /> _ another underline _";echo "String before pre-format:<br />".$string."<br />";$regEx = array("/_([a-z0-9\s,\.]+)_/i","/\/([a-z0-9\s,\.]+)\//i","/\*([a-z0-9\s,\.]+)\*/i");$replace=array("<u>\\1</u>","<i>\\1</i>","<b>\\1</b>");$string = preg_replace($regEx,$replace,$string);echo "string after format:<br />";echo $string; Works just fine for me, although i'm sure that there's an easier way to include punctuation, i just dont know how. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.