Solved

string replace

Posted on 2009-05-09
2
247 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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

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 how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

760 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now