Search code examples
phpstringreplacehyperlinkplaceholder

Replace square braced placeholders with HTML hyperlinks using the placeholder value in the URL querystring and as the clickable text


i have a long string like

$str = "this is [my] test [string] and [string] is very long [with] so many pwords]"

i know str_replace function, but when i replace

$str = str_replace( "[", "<a href=\"/story.php?urdu=",$str;
$str = str_replace( "]", "\"></a>", $str;

I got this result

<a href="/index.php?word=test"></a>

but I want this result for each word in []:

<a href="/index.php?word=test">test</a>

Solution

  • You should use preg_replace() for this one.

    Code

    <?php
        function replace_matches($matches) {
            $text = htmlspecialchars($matches[1]);
            $url = urlencode($matches[1]);
            return "<a href=\"/story.php?urdu={$url}\">{$text}</a>";
        }    
        $str = "this is [my] test [string] and [<script>alert(1)</script>] is very long [with] so many pwords]";
        $str = preg_replace_callback("%\[(.+?)\]%", "replace_matches", $str);
    
        echo $str;
    ?>
    

    Working Example