How to remove a part of the string at the beginning or after the space?

2

I need to change names beginning with HE by E such as

HELIANE HELIAS

for

ELIANE ELIAS

But it can be

GUILHERME HENRIQUE

and switch to

GUILHERME ENRIQUE

    
asked by anonymous 10.08.2016 / 22:34

2 answers

3

If you only want to replace HE at the start of names / words use \b , so no characters are substituted in the middle of the string.

Example - ideone

<?php
   //exemplo 1
   $str = 'HELIANE HELIAS';
   $str = preg_replace('/\bHE/','E', $str);
   echo $str. PHP_EOL; //ELAINE ELIAS

   //exemplo 2
   $str = 'GHELIANE GHELIAS';
   $str = preg_replace('/\bHE/','E', $str);
   echo $str; //GHELIANE GHELIAS

Related:

What is a boundary (b) in a regular expression?

    
10.08.2016 / 23:43
2

Can do with preg_replace , I created an example function:

function removeHe($nome) {
    $pattern = '/[^a-zA-Z ]{1}H(e)/i';
    $replace = '$1';
    return ucwords(preg_replace($pattern, $replace, $nome));
}

Or if you prefer, a reduced version of the function:

function removeHe($nome) {
    return ucwords(preg_replace('/[^a-zA-Z ]{1}H(e)/i', '$1', $nome));
}
  

Usage:

echo removeHe('Guilherme Henrique');
echo '<br/>';
echo removeHe('HELIANE HELIAS') ;
echo '<br/>';
echo removeHe('Heliane Helias') ; // iniciando com he
echo '<br/>';
echo removeHe('Marcos Porche') ; // terminado com he

Return:

  

Guilherme Henrique

     

HELIANE HELIAS

     

Heliane Helias

     

Marcos Porche

I hope I have helped!

    
10.08.2016 / 22:49