preg_replace to replace spaces by dashes

1

I need to get a news headline and display the URL. To do this, I want to fetch the title in the database and replace every blank space between one word and another, with a hyphen. For example: "News test" would read "Test-news".

I've tried:

$titulo_novo = preg_replace('<\W+>', "-", $titulo); 

//$titulo é o titulo vindo do banco de dados
    
asked by anonymous 28.04.2016 / 16:04

1 answer

3

The solution is very simple using preg_replace . If you just wanted to put the title as URL by converting spaces to hyphens, just add:

$titulo_novo = preg_replace('/[ -]+/' , '-' , $titulo);

But if you want something complete that also removes and converts accents, you can use:

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

echo $titulo_novo; //pode remover essa linha, é só pra mostrar como ficou.
    
28.04.2016 / 16:37