Solved

string replace

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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

Suggested Solutions

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

749 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