douboshan1466 2012-05-23 15:48
浏览 9

缩短此功能

I wrote this code to prepare a title for a link, but I think it is a bit bulky and am wondering if anyone with a better understanding of regex would be able to reduce the following function (by merging the relevant preg_replaces). I need it to strip all current hyphens, strip multiple spaces, ensure that it is solely alphanumeric apart from the space-replacing hyphen, replace all spaces with a single hyphen and ensure that the string doesn't start with a hyphen:

function prepareURLTitle($title)
{

return preg_replace("/\A-/", "", str_replace(" ", "-", preg_replace("/[^a-zA-Z0-9\s]/", "", preg_replace('/\s\s+/', ' ', preg_replace('/\s?-/', '', $title)))));

}

An example of input and it's output:

Input:

BRAND NEW - Gloves, 2 pack //Multiple spaces are in here but the blockquote won't allow me to display them

Output:

BRAND-NEW-Gloves-2-pack

  • 写回答

4条回答 默认 最新

  • donglei7152 2012-05-23 15:51
    关注
    function prepareURLTitle($title)
    {
       return preg_replace( "/[^a-zA-Z0-9]/", "-",str_replace("-", "",  $title));
    }
    

    DEMO: http://codepad.org/lPSQQBys

    OUTPUT:

    BRAND-NEW--Gloves--2-pack

    评论

报告相同问题?