Hafiz
Hafiz

Reputation: 43

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>

Upvotes: 0

Views: 439

Answers (3)

mickmackusa
mickmackusa

Reputation: 47854

Here is a modernized demonstration of using to preg_replace_callback() with arrow function syntax to replace each placeholder with a hyperlink where the URL querystring is reliably constructed by calling http_build_query() and the visible text of the hyperlink is HTML-encoded by htmlspecialchars().

Code: (Demo)

$str = "this is [my] test [string] and [<script>alert(1)</script>] is very long [with] so many pwords]";
echo preg_replace_callback(
         "#\[([^\]]+)]#",
         fn($m) => sprintf(
             '<a href="/story.php?%s">%s</a>',
             http_build_query(['word' => $m[1]]),
             htmlspecialchars($m[1])
         ),
         $str
     );

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174947

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

Upvotes: 1

knittl
knittl

Reputation: 265141

$str = preg_replace_callback(
  '/\[([^\]]*)\]/',
  function($matches) {
    return sprintf('<a href="/index.php?word=%s">%s</a>',
      urlencode($matches[1]),
      htmlspecialchars($matches[1]));
  },
  $str);

Upvotes: 1

Related Questions