Remove all punctuation from php string for friendl

2019-07-28 02:38发布

问题:

So, I've seen a ton of "solutions" on this site, but none of them seem to work fully for me. I would like to strip all punctuation from a post name so that the system can dynamically create urls for each post. I found an article by David Walsh that provides a step by step tutorial on how this can be achieved. However, not everything gets stripped. Here is a link to the article (just in case): http://davidwalsh.name/php-seo.

Here's the code I've altered to remove all punctuation:

$return = trim(preg_replace('/[^a-z0-9]+/i'," ", strtolower($post_name)));

Here's an example post name: Testing's, this & more!

Results when I echo the url: testing-039-s-this-amp-more.php

I'm not sure why it's keeping the html code for the ampersand and the single quote. Any ideas?!?

回答1:

Looks like the data is run through htmlspecialchars() or htmlentities() somewhere. Undo that with htmlspecialchars_decode() or html_entity_decode() first:

$return = trim(preg_replace('/[^a-z0-9]+/i'," ", strtolower(htmlspecialchars_decode($post_name))));


回答2:

/**
  * prepares a string optimized for SEO
  * @see https://blog.ueffing.net/post/2016/03/14/string-seo-optimieren-creating-seo-friendly-url/
  * @param String $string 
  * @return String $string SEO optimized String
  */
function seofy ($sString = '')
{
    $sString = preg_replace('/[^\\pL\d_]+/u', '-', $sString);
    $sString = trim($sString, "-");
    $sString = iconv('utf-8', "us-ascii//TRANSLIT", $sString);
    $sString = strtolower($sString);
    $sString = preg_replace('/[^-a-z0-9_]+/', '', $sString);

    return $sString;
}

// Example
seofy("Testing's, this & more!"); // => testing-s-this-more

@see

  • https://blog.ueffing.net/post/2016/03/14/string-seo-optimieren-creating-seo-friendly-url/
  • http://php.net/manual/en/function.preg-replace.php#122374


标签: php regex url seo