Keeping upper or lower case while performing str_replace [ PHP 8.0 ]

Viewed 75

I am presently giving the command:

<?php echo str_ireplace( $url['word']['word'] , ( '<strong>' . $url['word']['word'] . '</strong>' ) , $url['word']['question'] ); ?></p>

I am using this in a "Word Of The Day" section of my web site. The purpose is that the word being used gets displayed in bold when viewed on the web page. For example:

What is the next **Aspiration** in your life you are working towards?

What I am really wanting to do is find a better way of inserting the <strong> tag around the word of the day. Right at the moment I have stored the words all with capitalization. I am hesitant to include HTML in the actual table so I can format this appropriately depending on any programming changes in the future. From the above example Aspiration is capitalized. But the "question" in the database is:

What is the next aspiration in your life you are working towards?

My database table structure is:

reference bigint
word text
question text
add_date timestamp with time zone
membership_reference

Is there a better way to add the <strong> and </strong> tags?

1 Answers

You'll want to check for word boundaries, not just any arbitrary match. Note what happens if your word is aspiration and your sentence is:

What is the next exaspiration in your life you are working towards?

Then you get a partial match:

What is the next ex<strong>aspiration<strong> in your life you are working towards?

To avoid this, you can use the \b regex pattern, and to make it case insensitive, you can use the /i modifier. Then, to preserve the case of the replaced word, capture the matched text with parens and replace with the matched text placeholder \1 instead of whatever casing the original source word had:

preg_replace('/\b(' . $word . ')\b/i', '<strong>\1</strong>', $question);

This yields:

This <strong>aspiration</strong> is lowercase.
<strong>Aspiration</strong> remains caps here.
But exaspiration does not get tagged.

I'd also recommend using something like <span class="word-of-the-day"> instead of <strong> -- then you can change your styling in CSS and you don't have to edit source code.

Related