Search code examples
phpstr-replacestrpos

Remove link if contains specific string


I have this PHP code where a specific word is converted to link before sending in email.

$message = str_replace(
           'hello',
           '<a id="get-ahead-link" style="color: #ffa503;" href="https://somelink.com"> hello </a>',
           $message,
           $count);

The code above is completely working but I got an issue when a link with the word 'hello' is already included.

Example:

hello world. Please visit my site: http://helloworld.com.

This becomes:

hello world. Please visit my site: http://helloworld.com.

But what I need:

hello world. Please visit my site: http://helloworld.com.

Is this possible? What am I missing with my work?


Solution

  • You could use preg_replace (replacement using regular expressions) and surround your string with (?<=^|\s) ("is either at the beginning of the string or preceded by a space character") and \b (word boundaries):

    $message = preg_replace(
      '/(?<=^|\s)hello\b/', 
      '<a id="get-ahead-link" style="color: #ffa503;" href="https://somelink.com">hello</a>', 
      $message, 
      -1, 
      $count
    );
    

    Demo: https://3v4l.org/SknUT

    Note: I left the additional parameters to retrieve $count.

    Other (unrelated) note: such inline HTML styles should be avoided in most cases.