How do I delete whitespace around a given character?

1

How can I via preg_replace delete spaces between /

For example:

Comercial / Vendedor to Comercial/Vendedor

Compras / Vendas to Compras/Vendas

I want this because users always type the wrong one.

Here is the template I use to delete rows by email. What would be the expression to do what I want above?

function filterEmail($text) {
    return preg_replace('/(.*)[a-z0-9\.\_\-]+@[a-z0-9\.\_\-]+\.[a-z]+(.*)/i','', $text);
}
    
asked by anonymous 06.04.2016 / 19:38

3 answers

3

If it's just to eliminate the space between the slashes, use str_replace .

$str = "Comercial / Vendedor";
echo str_replace(" / ", "/", $str);

Output:

  

Commercial / Salesperson

See the ideone .

    
06.04.2016 / 19:46
3

The answer from @MarceloDeAndrade is the most appropriate way for the exact case of the problem (and I already received my +1), but just to complement, it follows a version with RegEx taking advantage of its potential: / p>

$str = 'Comercial /Vendedor - Compras/ Vendas - Um     /   Dois';
$str = preg_replace('(\s*/\s*)','/', $str);
echo $str;

In this case, we are capturing situations where space can vary in quantity, or simply does not exist.

  • It works if you have more than one space ( a / b );

  • It works if you do not have space on either side ( a /b or a/ b );

  • Capture other types of white space (tabs etc).

See working at IDEONE .


But as the PHP manual says about str_replace , it is Always remember that:

  

If you do not need special substitution rules (such as regular expressions), you could always use this function instead of ereg_replace () or preg_replace ().

    
06.04.2016 / 20:28
3

I recommend using str_replace because of performance. Just for the sake of curiosity, this is what you would do if you were to use preg_replace :

$txt = "Compras / Vendas";
echo preg_replace("# / #g", "", $txt);

Notice that I used # as the regex delimiter, instead of the / that is more usual. This is because / would conflict with our regex, which also looks for a slash in the text. However, if you wanted to use / as a delimiter, you could escape the pattern using the backslash:

echo preg_replace("/ \/ /g", "", $txt);

We can use multiple symbols as delimiters (eg @ , + , % ). You can also use open and close pairs, such as () , {} , [] , <> .

    
06.04.2016 / 20:13