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
Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php
By Dave - November 28, 2018
Hi KennyH,
Yea, Jerry has the right idea. The "regular expression" matching functions let you match a pattern instead of just some characters. Try this:
$tags = preg_split("/\s*,\s*/", $social_media_postsRecord['hashtags']);
This splits your string into an array of tags. /s means space character and * means 0 or more. So if will match a comma surround by zero or more spaces on either side. For more details: http://php.net/manual/en/function.preg-split.php
Then to display it you could use something like this:
<?php foreach ($tags as $tag): ?>
<li class="list-inline-item">
<a href="#" class="badge badge-dark badge-md badge-pill">#<?php echo $tag; ?></a>
</li>
<?php endforeach ?>
Note that you could also just swap str_replace for preg_replace, but you might find using preg_split() produces cleaner code. Either way is fine.
Hope that helps!
interactivetools.com