How can I add an HTML tag to specific words in a string and print them along with the rest of the words in PHP?

one text

Solution:

I think first learn how to do it with str_replace.

Here is a more advanced example using pre_replace which you can study after.

    $string = "Every #time it #rains there is #flood";

    echo preg_replace("/(#\w+)\s?/", "<a href=\"\${0}\">\${0}</a>", $string);

Here is an example with the first word done for you. You can complete the two arrays.

    $string = "Every #time it #rains there is #flood";
            
    $find = [
    "#time",
    ];

    $replace = [
    "<a href='abc.com'>#time</a>",
    ];

    $stringreplaced = str_replace($find,$replace,$string);

    echo $stringreplaced;

Source