[英]How to ignore a single character in RegEx
如何忽略單引號?
function FixNameForLink($str){
// Swap out Non "Letters" with a -
$text = preg_replace('/[^\\pL\d]+/u', '-', $str);
// Trim out extra -'s
$text = trim($text, '-');
// Convert letters that we have left to the closest ASCII representation
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// Make text lowercase
$text = strtolower($text);
// Strip out anything we haven't been able to convert
$text = preg_replace('/[^-_\w]+/', '', $text);
return $text;
}
我給我起了個名字,叫Steven's Barbecue
( Steven's Barbecue
,我想將其轉換為正確的鏈接,例如steven-s-barbecue
,但是以某種方式我需要能夠將'轉換為另一個字符,例如_
為了澄清(避免混亂...),鏈接需要為steven_s-barbecue
解決方案是允許在最初的替換中使用引號字符,然后在末尾用_替換。 下面的例子:
<?php
function FixNameForLink($str){
// Swap out Non "Letters" with a -
$text = preg_replace('/[^\pL\d\']+/u', '-', $str);
// Trim out extra -'s
$text = trim($text, '-');
// Convert letters that we have left to the closest ASCII representation
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// Make text lowercase
$text = strtolower($text);
// ' has been valid until now... swap it for an _
$text = str_replace('\'', '_', $text);
// Strip out anything we haven't been able to convert
$text = preg_replace('/[^-_\w]+/', '', $text);
return $text;
}
var_dump(FixNameForLink("Steven's Barbecue")); // steven_s-barbecue
運行str_replace
嗎?
$text = str_replace("'", '_', $str);
$text = preg_replace('/[^_\\pL\d]+/u', '-', $text);
為了安全起見,您也可以在所有功能都運行到最終產品之后運行urlencode()
,因為您嘗試使用破折號而不是%20
作為空格
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.