Forum Moderators: coopster

Message Too Old, No Replies

Complex preg replace usage

I need to make changes to the matched text

         

ntbgl

12:42 am on Jul 6, 2009 (gmt 0)

10+ Year Member



I have a string that looks like this:

$before="[[Lorem ipsum]] dolor sit amet, [[consectetur¦adipiscing elit]]. Aliquam mattis [[vestibulum nil]]es, at tincidunt [[eros¦commodo eu]].";

I'm trying to use pre_replace to change this into this:

$after="<a href="/Lorem_ipsum">Lorem ipsum</a> dolor sit amet, <a href="/Consectetur">adipiscing elit</a>. Aliquam mattis <a href="/Vestibulum_nil">vestibulum niles</a>, at tincidunt <a href="/Eros">commodo eu</a>.";

I'm using preg_replace to make everything between double square brackets into links, but I'm having a hard time trying to get the spaces in the URL to become underscores (without all the spaces in the string becoming underline).

$after=preg_replace("/\[\[(.*)\]\]/iU","<a href=\"/$1\">$1</a>",$before);

I imagine once I figure out how to make changes to the isolated part of the string (the matched part), I could use something like ucfirst(str_replace(" ","_",$1));

Beyond that, I don't have a clue how to match when the link text and url are different ([[consectetur¦adipiscing elit]]) or when the link text falls outside of the double square bracket but before a space ([[vestibulum nil]]es), worse still, when it's a combination of both.

Any advice is much appreciated. Thanks.

andrewsmd

8:10 pm on Jul 6, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Does your string ALWAYS appear exactly that way? And if so is it like this
"[[Lorem ipsum]] dolor sit amet, [[consectetur¦adipiscing elit]]. Aliquam mattis [[vestibulum nil]]es, at tincidunt [[eros¦commodo eu]].[[Lorem ipsum]] dolor sit amet, [[consectetur¦adipiscing elit]]. Aliquam mattis [[vestibulum nil]]es, at tincidunt [[eros¦commodo eu]].";

or like this

"[[Lorem ipsum]] dolor sit amet, [[consectetur¦adipiscing elit]]. Aliquam mattis [[vestibulum nil]]es, at tincidunt [[eros¦commodo eu]]. Aliquam mattis [[vestibulum nil]]es, at tincidunt [[eros¦commodo eu]].Aliquam mattis [[vestibulum nil]]es, at tincidunt [[eros¦commodo eu]]."

It would probably help if you didn't use lorem impsum and actully put a longer list of actual data you will be dealing with.