How to delete whitespace around a given character?

Asked

Viewed 317 times

1

How can I via preg_replace delete spaces between /

For example:

Comercial / Vendedor for Comercial/Vendedor

Compras / Vendas for Compras/Vendas

I wish this because users always type wrong.

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

function filterEmail($text) {
    return preg_replace('/(.*)[a-z0-9\.\_\-]+@[a-z0-9\.\_\-]+\.[a-z]+(.*)/i','', $text);
}
  • 6

    I do not understand why the staff is negativizing this question. It seems to be a valid question like any other on the site.

  • 3

    To use regex for this is an exaggeration, but this who has to explain is the answers and/ or comments. I don’t think it’s a case for negativity (and positive if it’s "just to compensate", because then it’s a mistake on top of another).

3 answers

3

If it is only to eliminate the space between the bars, use the str_replace.

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

Exit:

Commercial/Seller

See on ideone.

3

I recommend using str_replace because of the performance. Just out 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 delimiter of the regex, instead of the / which is more usual. That’s because / would conflict with our regex, which also searches for a bar in the text. Still, if you wanted to use / as delimiter, it would be possible to escape the Pattern using the backslash:

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

We can use various symbols as delimiters (e. g. @, +, %). It is also possible to use opening and closing pairs, such as (), {}, [], <>.

3

The @Marcelodeandrade answer is the most appropriate way for the exact case of the problem (and already received my +1), but only to complement, follows a version with Regex harnessing its potential:

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

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

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

  • works if you don’t have room anywhere ( a /b or a/ b );

  • captures other types of white space (tabulation etc).

See working on IDEONE.


But as you say the PHP manual itself about str_replace, it is always good to remember that:

If you don’t need special substitution rules (like regular expressions), you could always use this function instead of ereg_replace() or preg_replace().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.