Remove Accents and Transform Spaces in PHP Traces

2

I updated my PHP and my next Script which I used to transform text without accents, and the dashed spaces (-) no longer works in PHP because ereg_replace is obsolete.

>
<?php
    $variavel = "Céu Azul";
    $variavel_limpa = strtolower( ereg_replace("[^a-zA-Z0-9-]", "-", strtr(utf8_decode(trim($variavel)), utf8_decode("áàãâéêíóôõúüñçÁÀÃÂÉÊÍÓÔÕÚÜÑÇ"),"aaaaeeiooouuncAAAAEEIOOOUUNC-")) );
    echo $variavel_limpa; // ceu-azul
?>

What would be the solution for me to perform the transformation of this string (removing accents and dashing between spaces) to work in PHP 7.

    
asked by anonymous 14.04.2018 / 23:37

3 answers

2

Use preg_replace , supported in PHP 7 as well.:

$variavel_limpa = strtolower( preg_replace("/[^a-zA-Z0-9-]/", "-", strtr(utf8_decode(trim($variavel)), utf8_decode("áàãâéêíóôõúüñçÁÀÃÂÉÊÍÓÔÕÚÜÑÇ"),"aaaaeeiooouuncAAAAEEIOOOUUNC-")) );
  

You must also include the // delimiters in the regex.

Test here

    
14.04.2018 / 23:41
2

Since% w / o has been deprecated, it is necessary to replace with another function. In place of this function, you can use ereg_replace , the working is very similar and the rules - practically - are the same.

To remove characters with accents, you can use the preg_replace function, so you will "translate" some letters, for example:

<?php

$text = "O céu azul foi visto por André, João…";

/**
 * Converte a String para ASCII
 * O //TRANSLIT irá tentar traduzir os caracteres, por exemplo è => "'e"
 * Após isso, aplicamos uma expressão regular para deixar somente 
 * \w = Números, Letras e "underline"; e \s = espaço
 */
$text = preg_replace("/[^\w\s]/", "", iconv("UTF-8", "ASCII//TRANSLIT", $text));

/* Com o str_replace podemos substituir os espaços 
 * deixados na linha anterior, pelo hífen
 */
$text = str_replace(" ", "-", $text);

/* Transformamos todo o texto em minúsculo */
$text = strtolower($text);


echo $text;
// Output: o-ceu-azul-foi-visto-por-andre-joao

Demo: link

    
15.04.2018 / 00:02
0

strtolower - Converts a string to lowercase

strtr - translates certain characters into a string

utf8_decode - converts a string with ISO-8859 characters -1 encoded with UTF-8 for single-byte ISO-8859-1.

$variavel = "Céu Azul";
$variavel_limpa = strtolower(strtr(utf8_decode($variavel), utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ '), 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY-'));

example - PHP Sandbox

  

strtr and str_replace , essentially do the same thing, strtr is a bit faster for simple operations.

For simple things any attempt to use regular expression fatally will be slower. Source strong>

    
03.01.2019 / 00:59