Parts of string that dont HAVE to be there

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
markusn00b
Forum Contributor
Posts: 298
Joined: Sat Oct 20, 2007 2:16 pm
Location: York, England

Parts of string that dont HAVE to be there

Post by markusn00b »

I was intruiged as to how to build a parse that would run like bbcode does.

So's i had a go at it, somewhat shakily and naively.

As was expected, i hit a snare: when searching for a [url=http...] i could easily turn this into a real url using

Code: Select all

 
preg_replace('#\[url=(.*)\](.*)\[/url\]#', "<a href='$1'>$2</a>", $_string);
 
The problem was hit when i wanted to give the user the option of an extra - the 'target' attribute. I managed to get it working using this:

Code: Select all

 
preg_replace('#\[url=(.*) target=(.*)\](.*)\[/url\]#', "<a target='$2' href='$1'>$3</a>", $_string);
 
but obviously if the target isn't present problems will arise.

So, my question is: how can i have extra(s*) in the url that dont have to be there?

And how would i go about adding others such as: title, name, id... etc.

Kind regards!

p.s. im terrible of thinking up thread titles! :(
User avatar
HCBen
Forum Commoner
Posts: 33
Joined: Thu Jun 22, 2006 3:15 pm
Location: Indiana

Re: Parts of string that dont HAVE to be there

Post by HCBen »

If "url" is the only attribute string that's not equivalent to an attribute in an anchor tag, all other attributes you include in your custom url tag can be matched for in entirety (assuming all other attributes are valid anchor tag attributes).

Something like this for example:

Code: Select all

preg_replace('#\[url=(.*)(\s*target=[\w+])*(\s*name=[\w+])*\](.*)\[/url\]#','<a href="$1" $2 $3>$4</a>',$_string);
It's not ideal and if you use this you'll need to tweak it, but this example should give you the idea.

Prost!
Ben
Post Reply