user3745594 user3745594 - 4 months ago 8
PHP Question

PHP Regex to get a name from a url tag

There is a lot of Regex to get links or a value from url tags

<a href
, but what about extract a value from url tags like this

$text = '[URL="http://google.com"]ANY THING[/URL]';


if i want get value
ANY THING
from this url tag , what Regex Can I use ?

Answer

You can use this one

'/\[URL[^]]+\](?P<name>[^\[]+)\[\/URL\]/'

But you should probably learn Why.. Here is a good tester that shows that regx at work

https://regex101.com/r/hS0sO5/1

Traditionally this is called BBcode ( builtin board code )

https://en.wikipedia.org/wiki/BBCode

There are full PHP implementations of this sort of thing you can use besides regx

If you want both ( optionally the url ) you can use this one

'/\[URL(?:\=\"(?P<url>[^"]+)\")?\](?P<name>[^\[]+)\[\/URL\]/'

And here is that one at work

https://regex101.com/r/hS0sO5/2

That last one does require the " around URL, I have seen them done with ' or no quotes at all.