Sami Sami - 2 months ago 15
PHP Question

PHP - Preg replace pattern to replace / or & with space or without space if necessary

What is the

preg_replace
pattern to replace the
/
or
&
with
and
with and without space? The pattern should be able to replace all the below examples:

This is J/J.
to
This is J and J.
.
J/J, Y& S, and U / A are names.
to
J and J, Y and S and U and A are names.
.
What does J /J or J & E mean?
to
What does J and J or J and E mean?

Answer

Try this:

<?php
   $text = "J/J, Y& S, and U / A are names.";
   $result = preg_replace('~[/&]~', ' and ', $text, -1);
   echo $result;
Comments