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

Asked

Viewed 536 times

2

I need to exchange names started with HE for E as for example

HELIANE HELIAS

for

ELIANE ELIAS

but it may be

WILLIAM HENRY

and switch to

GUILHERME ENRIQUE

2 answers

3


If it’s just to replace the HE at the beginning of names/words use the \b, so no middle characters are replaced in 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’s the use of a Boundary ( b) in a regular expression?

  • It worked, it was worth too much, to learn even regular expression, it helped a lot

2

You can do it using the preg_replace, 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));
}

Use:

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’ve helped!

  • this did not work, in fact all the names are uppercase for example GUILHERME HENRIQUE even changing the $Pattern = '/H(e)/'; for $Pattern = '/H(E)/'; still replaces being GUILERME ENRIQUE

  • only add the "i" at the end of the Pattern, I’ve updated the answer.

  • keeps going wrong until the return of the site went wrong gets guillermo

  • On my server works correctly. What is your configuration: Webserver, PHP version, etc.?

  • What error is appearing?

  • Ubuntu server lts standard, keeps changing the names with him

  • Solved, please let me know if it worked.

  • Remember to test names finished with HE, example: Marcos Porche

Show 3 more comments

Browser other questions tagged

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