Jump to content

[SOLVED] ereg_replace() question


ballhogjoni

Recommended Posts

I have a string "Crumbling Credit Economy: What should YOU do?" and I want to replace the spaces with a hyphen(-) and get rid of all the other characters except the numbers and letters. How would I do that?

 

code so far:

$sTitleUrl = ereg_replace("[^A-Za-z0-9]", "", str_replace(" ", "-", $sTitle));

Link to comment
https://forums.phpfreaks.com/topic/120934-solved-ereg_replace-question/
Share on other sites

Should be in Regular Expressions section but it doesn't matter.

 

<?php

$str = "Crumbling Credit Economy: What should YOU do?";

//Remove all unwanted characters, keeping spaces as well!
$str = preg_replace("#[^a-zA-Z0-9 ]+#s", "", $str);
//Now add in hyphens for spaces
$str = str_replace(" ", "-", $str);

//One Line?
$oneLine = preg_replace("#[^a-zA-Z0-9\-]+#s", "", str_replace(" ", "-", $str));

echo $str;

?>

 

The one line solution is okay, but we are allowing hyphens in the expression.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.