I am having a hard time figuring this out:
I have a string ($data) which contains some links formatted this way:
[pagelink]Folder/File[/pagelink]
The $data contains multiple of these links.
I need to replace these links with actual html links and I have this code to do it (which works):
$data = preg_replace('/\[pagelink\](.*?)\[\/pagelink\]/is','<a href="$1">$1</a>',$data);
Now I would like to remove all the "Folder" instances from the part of the link that is showed to the user without actually altering the link itself; in other words if the link is this:
[pagelink]Folder/File[/pagelink]
I would like it to become this:
<a href="Folder/File">File</a>
What I tried is this:
$data = preg_replace('/\[pagelink\](.*?)\[\/pagelink\]/is','<a href="$1">'.( strstr($1) === false ? $1 : str_replace('/','',strstr($1)) ).'</a>',$data);
but I get a bunch of errors so I guess I can't use back references this way.
Could you guys help me out please? Thanks
Revise your regular expression so the folder and file are in separate capture groups.
$data = preg_replace('#\[pagelink\](.*?/)?([^/]*?)\[/pagelink\]#is','<a href="$1$2">$2</a>',$data);
Capture group 1
gets Folder/
, capture group 2
gets File
.
you can do that:
$data = preg_replace('~\[pagelink](/?(?>[^[/]+/)*([^/[]+))\[/pagelink]~', '<a href="$1">$2</a>', $data);
That looks like BBCode. PHP has an extension for that.
http://www.php.net/manual/en/function.bbcode-create.php
One of the comments links to a PHP implementation of the library.
If you need logic to compile the replacement for a preg_replace() use preg_replace_callback().
Thank you for your answer guys! Actually I found another solution as well.
preg_replace_callback also works for this and I came up with this which also works:
$data = preg_replace_callback('/\[pagelink\](.*?)\[\/pagelink\]/is',function ($matches) { return '<a href="'.$_SERVER['PHP_SELF'].'?p='.$matches[1].'">'.( strstr($matches[1],'/') === false ? $matches[1] : str_replace('_',' ',str_replace('/','',strstr($matches[1],'/'))) ).'</a>'; },$data);
however your suggestions are great and very helpful! Thanks!