Concatenate letters/words if it contains "&" and there is space between them

Asked

Viewed 145 times

1

How to concatenate letters/words if it contains "&" and there is space between them?

Example:

A & E COMERCIO DE ALGUMA COISA LTDA
EMPRESA P & C CONSTRUCAO LTDA
CAMARAO & CIA FULANO DE TAL - ME

// OUTPUT
A&E COMERCIO DE ALGUMA COISA LTDA
EMPRESA P&C CONSTRUCAO LTDA
CAMARAO&CIA FULANO DE TAL - ME

2 answers

5


Can use preg_replace to replace the occurrence of  & .

preg_replace("/ *& */", "&", $string);

With this regex you will replace the spaces that exist before and after the &.

* : indicates that the previous parameter occurs none or several times.

In this case we have it can exist: AS& DFG, AS & DFG, AS &DFG, AS&DFG, in all these cases it will match and run replace.

Example:

$example = "A   &   E COMERCIO DE ALGUMA COISA LTDA";
$out = preg_replace("/ *& */", "&", $example);
echo $out; // A&E COMERCIO DE ALGUMA COISA LTDA

Handbook of preg_replace

  • Good @Luishenrique, dear as it would be if it were the following CAMARAO &CIA FULANO-ME or CAMARAO& CIA FULANO-ME with spaces on only a few sides?

  • You can use preg_replace("/ ?& ?/", "&", $example);. The ? matches in 0 or 1 instance, while the + 1 or more. Another option is to replace the ? for *, which means 0 or more occurrences.

  • @smigol updated the answer considering the case that one side is already concatenated.

  • brigado @Luishenrique

0

I don’t know about PHP, but try this on:

To\040&\040AND TRADE IN SOMETHING LTDA CONSTRUCTION COMPANY LTD

or

To\s&\sAND TRADE IN SOMETHING LTDA CONSTRUCTION COMPANY LTD

Browser other questions tagged

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