Home > Blockchain >  Find and replace keyword in a string with PHP
Find and replace keyword in a string with PHP

Time:12-30

I have this code to find and replace some string if it's between some {{ and }}.

$string = 'This is my {{important keyword}}.';
$string = preg_replace('/{{(.*?)}}/', '<a href="$1">$1</a>', $string);
return $string;

How I can change the <a href="$1">$1</a> part to have something like this:

<a href="https://example.com/important-keyword">important keyword</a>

So the href needs to have the match item converted like a slug (words separated with a dash, no accent or special char).

Thanks.

CodePudding user response:

You have to use preg_replace_callback() to allow change on matches in a function.

See also use($url) to allow the function to access to the external variable.

Code:


$url = 'https://example.com';
$string = 'This is my {{important keyword}}.';

$string = preg_replace_callback('/{{(.*?)}}/', function($matches) use ($url) {
    $newURL = $url . '/' . str_replace(' ', '-', $matches[1]);
    return '<a href="' . $newURL . '">' . htmlentities($matches[1]) . '</a>';
}, $string);

echo $string;

Output:

This is my <a href="https://example.com/important-keyword">important keyword</a>.
  •  Tags:  
  • php
  • Related