从URL中删除特殊字符

时间:2010-04-22 09:22:57

标签: php string

我有一个产品数据库,我正在尝试将它们显示为干净的URL,下面是示例产品名称:

PAUL MITCHELL FOAMING POMADE (150ml)
American Crew Classic Gents Pomade 85g
Tigi Catwalk Texturizing Pomade 50ml

我需要做的是在URL结构中显示如下:

www.example.com/products/paul-mitchell-foaming-gel(150ml)

我遇到的问题是我想要做以下事情:

1.  Remove anything inside parentheses (and the parentheses)
2.  Remove any numbers next to g or ml e.g. 400ml, 10g etc...

我一直在试着尝试不同的字符串替换,但是无法正确使用它,我真的很感激一些帮助。

干杯

4 个答案:

答案 0 :(得分:3)

function makeFriendly($string)
{
    $string = strtolower(trim($string));
    $string = str_replace("'", '', $string);
    $string = preg_replace('#[^a-z\-]+#', '_', $string);
    $string = preg_replace('#_{2,}#', '_', $string);
    $string = preg_replace('#_-_#', '-', $string);
    return preg_replace('#(^_+|_+$)#D', '', $string);
}

此功能可帮助您清理网址。 (也清理数字)

答案 1 :(得分:3)

试试这个,

<?php
$url = 'http%3A%2F%2Fdemo.com';
$decodedurl= urldecode($url);
echo $decodedurl;
?

答案 2 :(得分:2)

$from = array('/\(|\)/','/\d+ml|\d+g/','/\s+/');
$to = array('','','-');

$sample = 'PAUL MITCHELL FOAMING POMADE (150ml)';
$sample = strtolower(trim(preg_replace($from,$to,$sample),'-'));
echo $sample; // prints paul-mitchell-foaming-pomade

答案 3 :(得分:0)

试试这个:

trim(preg_replace('/\s\s+/', ' ', preg_replace("/(?:\(.*?\)|\d+\s*(?:g|ml))/", "", $input)));

// "abc (def) 50g 500 ml 3m(ghi)" --> "abc 3m"