/    Sign up×
Community /Pin to ProfileBookmark

Regular Expression help

I have a regular expression that is used to find the BB code of a url within a string and replace it with an A tag. It works, however I am having a problem when there are two or more occurrences of the [Url] tag. I think it has something to do with the variables within the regular expression. I am not very familiar with it and could do with some help.

This is the regular expression at present:

[code=php]$string = preg_replace(‘/([URL=)(.+)(])(.+)([/URL])/’, ‘<a href=”\2″ target=”_blank”>\4</a>’, $string);[/code]

Thanks in advance

Ben

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@NogDogOct 27.2009 — You could add a [b]U[/b] modifier to toggle the greediness of your expression to be ungreedy.

PS: Depending where you are in your development cycle and how complex you expect your BBCode system to be, you might want to consider using the [url=http://pear.php.net/package/HTML_BBCodeParser]PEAR HTML_BBCodeParser package[/url].
Copy linkTweet thisAlerts:
@Benji6996authorOct 27.2009 — really sorry but I have no idea what that means, any chance you could explain. I am not very familiar with regex so need all the help I can get.

Thank you
Copy linkTweet thisAlerts:
@NogDogOct 27.2009 — After the closing delimiter of your regular expression ("/" in this case), you can add any number of pattern modifiers.
[code=php]
preg_replace('/foo*bar/U', 'fubar', $str);
[/code]
Copy linkTweet thisAlerts:
@Benji6996authorOct 27.2009 — Legend, I don't understand why it works, but don't care and am very happy. Thanks so much.
Copy linkTweet thisAlerts:
@NogDogOct 28.2009 — By making the pattern "ungreedy", the repetition operators like "*" and "+" are made to only match the minimum number of characters needed to fulfill that pattern. The default is to be "greedy" and match as much as possible.
×

Success!

Help @Benji6996 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.14,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...