0

I'm busy with a website and for an element I use preg_replace to replace all the spaces with a dash.

preg_replace('/\\s/', '-', $item_replace_en[0])

And this works great but now i have a new problem. A user enterd the following "Music / Film". the output is "Music-/-Film" and i want it to be "Music-Film".

How can I accomplish this?

1
  • 2
    Are you going to ask again when a user enters "Music, Film"? If not, take the time to specify what you want more accurately. Commented Jun 27, 2012 at 9:43

3 Answers 3

2

It looks like you're trying to generate a string that can be used as a URL.

There a numerous of scenarios that can happen when a user adds a title that you want to convert to a URL safe string. Someone could for instance use this:

Mess'd up --text-- just (to) stress /test/ ?our! `little` \\clean\\
url fun.ction!?-->"); 

Should return:

messd-up-text-just-to-stress-test-our-little-clean-url-function

Is your code ready for that? In that case you can use this function:

setlocale(LC_ALL, 'en_US.UTF8');
function toAscii($str, $replace=array(), $delimiter='-') {
    if( !empty($replace) ) {
        $str = str_replace((array)$replace, ' ', $str);
    }

    $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
    $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
    $clean = strtolower(trim($clean, '-'));
    $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

    return $clean;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use array in pattern and replacement text. For example

$pattern=array();
$pattern[0]="/\\s/";
$pattern[1]="/-\/-/";
$replace=array();
$replace[0]="-";
$replace[1]="-";
preg_replace($pattern, $replace, $item_replace_en[0]);

You can use as many patterns and replacement you want. For more info, refer to http://php.net/manual/en/function.preg-replace.php

Comments

0

Try this :

$returnValue = preg_replace('/(\\s\\/)?(\\s)/', '-',$item_replace_en[0]);

But this will not replace a string like "Music/ Film" or "Music /Film" or Music/Film.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.