I’m looking for nice regexp which could change me string from:
text text website.tld text text anotherwebsite.tld/longeraddress text http://maybeanotheradress.tld/file.ext
into bbcodes
text text [url=website.tld]LINK[/url] text text [url=anotherwebsite.tld/longeradress]LINK[/url] text text [url=http://maybeanotheradress.tld/file/ext]LINK[/url]
Could you please advice?
Even I vote for duplicate, a general suggestion: Divide and Conquer.
In your input string, all “URLs” do not contain any spaces. So you can divide the string into the parts that do not contain spaces:
As we know that each part is now potentially a link you can create your own function that is able to tell so:
The
in_arrayis just an example, you might be looking for regular expression based pattern matching instead. You can edit it later to fit your needs, I leave this as an exercise.As you can now say what a link is and what not, the only problem left is how to create a BBCode out of a link, that’s a fairly simple string operation:
So technically, all problems have been solved and this needs to be put together:
This already runs with your example string in question (Demo):
Output:
You then only need to tweak your
is_linkfunction to fullfill your needs. Have fun!