0

lLets say I have the following: $string = 'New+York-NY and where + is I want a \s and where - is I want ', '. The formatted string would appear as New York, NY.

Here is my code: $string = 'New+York-NY';

    $formattedLocation = preg_replace('/[+]/', ' ', $location);
    $formattedLocation = preg_replace('/-/', ', ', $formattedLocation);

    echo $formattedLocation;

This code works. However it is ugly and I would like to refactor it (if possible). I tried:

    $formattedLocation = preg_replace('/[+]/', ' ', $location) && preg_replace('/-/', ', ', $location);

This however doesn't work and is also still ugly. Should I be using a different function? Or should my regex be different? Please don't suggest wrapping it in a custom function (that's not the answer I'm looking for).

Thanks

4
  • Why do you consider your initial code ugly? It's readable and doesn't get more effective as long as you're using regexp. Commented Nov 14, 2013 at 2:38
  • for these kind of literal replacement you don't need to use preg_replace, use only str_replace that is faster. Commented Nov 14, 2013 at 2:40
  • I think it's ugly because it is repetitive. I would Like to shorten it without sacrificing simplicity. (if possible) Commented Nov 14, 2013 at 2:41
  • Wrap the replacement inside a function - that'S the usual way to ensure DRY. Or just don't use preg_repalce at all, see @p.s.w.g's answer. Commented Nov 14, 2013 at 2:42

1 Answer 1

1

For something this simple do you really need to use regular expressions? Try using str_replace:

$formattedLocation = str_replace(array('+', '-'), array(' ', ', '), $location);
Sign up to request clarification or add additional context in comments.

Comments

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.