Remove all punctuation from php string for friendl

2019-07-28 02:50发布

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?!?

标签: php regex url seo
2条回答
女痞
2楼-- · 2019-07-28 03:17

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))));
查看更多
迷人小祖宗
3楼-- · 2019-07-28 03:19
/**
  * 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

查看更多
登录 后发表回答