Solved

string replace

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to dynamically set the form action using jQuery.
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 …

734 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