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 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!

Dave Edis - Senior Developer
interactivetools.com