0

I have a strings of the form

"Look at this [website]{http://www.stackoverflow.com} 
or at this [page]{http://www.google.com}"

and I want to parse them with PHP to

"Look at this <a href='http://wwwstackoverflow.com'>website</a> 
or at this <a href='http://www.google.com'>page</a>"

How can I do this?

I though about using str_replace()but I dont know how to get the string between the brackets [].

Edit[26.08.2016]: The answer uses the PHP preg_replace method with Regular Expression. I didnt understand the given answer here, but it worked so I was happy But now I found this free tutorial that teaches you how to use Regular Expression. I found it very helpful. Especially when one wants to wrtie his own Regular Expression for a similar case.

11
  • 3
    Use this. Don't reinvent the wheel. Note: the syntax is slightly different for links. Commented Jun 28, 2016 at 14:03
  • 1
    @Script47: This isn't quite markdown syntax. Links are [Title](http://example.com). He'd have to replace the {} with () to use that. Commented Jun 28, 2016 at 14:04
  • 1
    @Script47 Unfortunately it's not quite Markdown. Adam, how about you actually do use an existing markup language? Commented Jun 28, 2016 at 14:05
  • With regex and preg_replace, I guess Commented Jun 28, 2016 at 14:05
  • 1
    @Rocket LOL. Even the emphasis was the same... Commented Jun 28, 2016 at 14:05

2 Answers 2

12

try it with preg_replace

$str="Look at this [website]{http://www.stackoverflow.com} or at this [page]{http://www.google.com}";

echo preg_replace('/\[(.*?)\]\{(.*?)\}/', "<a href='$2'>$1</a>", $str);

output:

Look at this <a href='http://www.stackoverflow.com'>website</a> or at this <a href='http://www.google.com'>page</a>

working Example: https://3v4l.org/jLbff

Sign up to request clarification or add additional context in comments.

Comments

1

This can be made easily by using preg_replace:

$pattern = "/(\\[([^\\]]+)\\]\\{([^\\}]+)\\})/";
$replacement = '<a href="$3">$2</a>';
$finalStr = preg_replace($pattern, $replacement, $yourString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.