Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

string replace

Posted on 2009-05-09
2
Medium Priority
?
292 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 39

Assisted Solution

by:Roger Baklund
Roger Baklund earned 284 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 320 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
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 count occurrences of each item in an array.

670 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