0

I came across a need today to use str_replace() to replace all hyphens in a string with spaces. Easy enough:

$string = "Some-test-string";
$string = str_replace('-', ' ', $string);

The thing is, using ' ' (string with empty space) in the "replacement" part of str_replace() just feels so dirty. Also seems brittle... Looks ugly too.

Is there no better option? I tried using a regex pattern in the "replacement" section but that didn't work, it came out literal.

Ideally, something like this would be great if possible:

$string = "Some-test-string";
$string = str_replace('-', '/\s/', $string);

Thanks!

Edited: Replaced all preg_replace() calls with str_replace() per suggestion.

5
  • 1
    You could use the hex value for space: preg_replace("/[-]+/", "\x20", $string);, but I don't know if that makes it cleaner Commented Jun 20, 2016 at 0:59
  • You would be better off with str_replace for this. I would not worry about it looking brittle or ugly so long as it works and is easily understood. I would use ' ' instead of " ". Commented Jun 20, 2016 at 1:09
  • Abdullah Bakhsh - That replaces with a literal \x20.. I should clarify that I want the space in the string... just trying to find an alternative way to represent the replacement in the preg_match() call. Commented Jun 20, 2016 at 1:13
  • Thanks John Fawcett - A few minutes after I posted this, I had changed it to str_replace because I realized the pattern was not advanced enough to require preg_match()... I'll update my question to reflect that! Commented Jun 20, 2016 at 1:14
  • Well \s is a space, tab, or new line, there's no way for PHP to know which character you are expecting there (or no way that I know of). The ' ' should be fine, you could input the HTML entity if this is for a browser,  , or  . Commented Jun 20, 2016 at 1:31

1 Answer 1

1

I see no reason to use regular expressions in this case. Why not use a simpler function, e.g. strtr()?

$string = "Some-test-string";
$string = strtr($string, '-', ' ');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ShiraNai7 - I had already switched out to using str_replace() once I realized that that regex pattern was too simple to require preg_replace(). I have updated my question to reflect that.

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.