str_replace with or without space

3 posts by 3 authors in: Forums > CMS Builder
Last Post: November 28, 2018   (RSS)

By KennyH - November 27, 2018

I have a blog section where the user can enter in keywords separated by commas in a text field. On the front end, I have a snippet that replaces the comma with a hashtag.

$hashtagbtn = '</a></li><li class="list-inline-item"><a href="#" class="badge badge-dark badge-md badge-pill">';
#<?php echo str_replace(", ","$hashtagbtn #",$social_media_postsRecord['hashtags']); ?>

This works great if the keywords are entered keyword1, keyword2, keyword3, keyword4 but it does not work if they are entered without spaces like keyword1,keyword2,keyword3,keyword4

What adjustment do I need to make in order to get the commas replaced with hashtags regardless if there is a space or not between the words?

By gkornbluth - November 27, 2018 - edited: November 27, 2018

Hi Kenny,

Just a guess, but:

str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f.{2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.

Try using preg_replace instead of str_replace and see what you get, or try using an array with str_replace

<?php str_replace(array(' ',' ',''), "$hashtagbtn #",$social_media_postsRecord['hashtags']); ?> (cobbled this together from something I found on the web, so no guarantees. Not sure about the number of single quotes in the array)

There are a bunch of recipes that discuss how to use regular expressions in my CMSB Cookbook. http://www.thecmsbcoobook.com

Hope that helps,

Jerry Kornbluth

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php