Question

So I'm making use of an API which encodes hyperlinks like this:

<u>\n\\*HYPERLINK \"http://www.youtube.com/watch?v=A0VUsoeT9aM\"A Youtube video</u>

And I want to convert them to just normal hyperlinks:

<a href="http://www.youtube.com/watch?v=A0VUsoeT9aM">A Youtube video</a>

I have some problems with that, because it uses a lot backslashes and quotations

So I thought maybe this would work:

 <?
$string = '<u>\\n\\\\*HYPERLINK \\"http://www.youtube.com/watch?v=A0VUsoeT9aM\\"A Youtube Video</u>';
$patterns = array();
$patterns[0] = '/(<u>....................)/g';
$patterns[1] = '/(\\\\")(?!http:\/\/)/g"';
$patterns[2] = '/(<\/u>)/g';
$replacements = array();
$replacements[2] = '<a href=';
$replacements[1] = '"';
$replacements[0] = '</a>';
echo preg_replace($patterns, $replacements, $string);
 ?>

But A. This just doesn't work:Warning: preg_replace(): Unknown modifier 'g' in X.php on line 11

and B. This doesn't work if the hyperlink text is a Url too

Was it helpful?

Solution

Try this:

$string = '<u>\\n\\\\*HYPERLINK \\"http://www.youtube.com/watch?v=A0VUsoeT9aM\\"A Youtube Video</u>';
$pattern = '/http[?.:=\\w\\d\\/]*/';
$namePattern = '/(?:")([\\s\\w]*)</';
preg_match($pattern, $string, $matches);
preg_match($namePattern, $string, $nameMatches);

echo 'a href="'.$matches[0].'">'.$nameMatches[1].'/a>';
//outputs <a href="http://www.youtube.com/watch?v=A0VUsoeT9aM">A Youtube Video</a>

Edit: changed so that the name is also extracted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top