Solved

string replace

Posted on 2009-05-09
2
267 Views
Last Modified: 2012-05-06
Hi,

I would like to replace all characters which are not letters nor numbers by a dash.
e.g. ?[ Hello ' !@ There :0 a !!
should be hello-there-0-a
(notice characters at beginning and end which arent numbers nor letters are ignored)
0
Comment
Question by:matthew016
2 Comments
 
LVL 39

Assisted Solution

by:Roger Baklund
Roger Baklund earned 71 total points
ID: 24343903
You can do it in multiple steps:
$str = "?[ Hello ' !@ There :0 a !!";
$str = preg_replace('/[^a-z0-9]+/i','-',$str);  # grops of invalid characters to single dash
$str = preg_replace('/-?([a-z0-9-]+[a-z0-9])-?/i','\1',$str); # remove dash at start and end
$str = strtolower($str);  # convert to lower case
echo $str; # hello-there-0-a

Open in new window

0
 
LVL 49

Accepted Solution

by:
Roonaan earned 80 total points
ID: 24348886
Instead of the second preg_replace, you can use trim with preg_replace:

$newStr = strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $str),'-'));

Regards

Arnoud
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question