Branko
Branko

Reputation: 149

PHP Regex match value in between two words and replace

Hello everyone what I want to achieve with php is to find a value in between two words (for all occurances) and replace this with another string, then remove the words around the value. Here's an example

$mysting = "[link]http://website.com[/link] bla bla bla bla [link]http://google.com[/link]";

What I want to achieve is make this string:

$newString = "<a href='http://website.com'>http://website.com</a> bla bla bla bla <a href='http://google.com'>http://google.com</a>";

How can I do this? This is what I have for now

preg_match("/(?<=[link])(.*)(?=[/link])/", $formData ,$match);

Thanks in advance!!

Upvotes: 0

Views: 665

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use preg_replace function:

$mysting = "[link]http://website.com[/link] bla bla bla bla [link]http://google.com[/link]";
$new_str = preg_replace("/\[link\]([^\[]+)\[\/link\]/", "<a href='$1'>$1</a>", $mysting);

print_r($new_str);

The output(as source code):

<a href='http://website.com'>http://website.com</a> bla bla bla bla <a href='http://google.com'>http://google.com</a>

Upvotes: 1

Related Questions