0

I have a string that I converted to an array. And the same string that I converted are keywords from a search that match keywords in a chunk of text.

I am wanting to with the array, use the keywords within it to add html tags to the chunk of text that have the similar keywords.

For example: keywords: dog, cat, cow

Text before: I own two dogs, four cats, and twenty cows.

Text after: I own two dogs, four cats, and twenty cows.

The chunk of text I have is in a variable.

But I am not sure what regex I exactly need, to use with preg_replace();.

<?php
    echo preg_replace($text, <b></b>, $keywords);
?>

Am I even going the right direction?

2 Answers 2

2

Create a regexp that uses alternation to match any of the words, by joining the words with |. In the replacement string, use $0 to refer to the part of the text that was matched.

$regexp = '/\b(' . implode('|', $keywords) . ').*?\b/i';
echo preg_replace($regexp, '<b>$0</b>', $text);

DEMO

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, it outputs the text, but none of the keywords have been wrapped by the <b></b> tags, I'm I missing something?
Works for me, see the demo.
my issue is that my keywords are both lowercase and uppercase, and the text may be the vice versa. How can adjust the Regex to match the text if either are upper or lower?
Add the i modifier to the regular expression to make it case-insensitive. That should be obvious. I've updated the answer.
Thanks! That was it. Regex is so confusing to me.
0

You can use this code:

echo preg_replace('/\b((?:cat|dog|cow)\S*)/i', `<b>$1</b>`, $keywords);

1 Comment

You can use \S instead of [^\s]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.