Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.