Msmit1993 Msmit1993 -3 years ago 93
PHP Question

Preg_replace multiple patterns

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?

Answer Source

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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download