preg_replace to replace spaces with dashes

Asked

Viewed 5,081 times

1

I need to get the headline of a story and run it through the URL. To do this, I want to search the title in the database and replace each blank space between a word and another with a hyphen. For example: "Newstest" would be "Newstest".

I tried to:

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

//$titulo é o titulo vindo do banco de dados
  • What have you tried? Do you have any code you’d like to show to help solve your problem? Increase the content of the question and you will get more specific answers ;)

  • I tried: $titulo_novo = preg_replace('< W+>', "-", $titulo); //$titulo is the title coming from the database.

  • Edit the question by adding this new friend info

  • 1

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

  • 1

    I got it. It only generated one error: accented characters (ã, ó, etc.) need to be normal, for example, will be replaced by ; ion by cao...

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 the 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.
  • 1

    It worked perfectly! Thank you Victor Gomes!

  • The ereg_* was depreciated, traded there for preg_replace() :P

  • Thanks @rray, corrected ;)

Browser other questions tagged

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