doulu4203 2018-10-08 11:02
浏览 39
已采纳

PHP preg_replace标题(非英文字符)来清理slug无法正常工作

I'm attempting to turn Titles to slugs

$string = "آزمون پادشاهی متحده";
$pattern = '/[`~!@#$%^&*()_|+\=?;:..’“\'"<>,€£¥•،٫؟»«\{\}\[\]\\\/]+/gi';
            $replacement = '';

            $slug = trim(preg_replace($pattern, $replacement, $string));
            $slug = str_replace(" ","-",$slug);

The end result should be آزمون-پادشاهی-متحده spaces replaced by hyphen.

Another example title: Great Britain slug: great-britain

How do i solve?

  • 写回答

1条回答 默认 最新

  • doujiunai2169 2018-10-08 11:17
    关注

    You need to apply the following fixes here:

    • Escape the backslash matching pattern, that is, '\\\\'
    • Remove the g modifier as it is not supported by PHP preg_replace (it replaces all occurrence in the input by default)
    • Add a u modifier to enable PCRE engine to parse both the pattern and input as Unicode strings.

    Use

    $string = "آزمون پادشاهی متحده";
    $pattern = '/[`~!@#$%^&*()_|+=?;:..’“\'"<>,€£¥•،٫؟»«{}[\]\\\\\/]+/ui';
    $replacement = '';
    
     $slug = trim(preg_replace($pattern, $replacement, $string));
     $slug = str_replace(" ","-",$slug);
     echo $slug;
    

    See the PHP demo.

    Note that [, =, { and } are not special inside a character class and need no escaping.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测