我们有这样的 url
http://www.example.co.uk/example-product-3436.html
我希望能够使用一个 php 脚本来删除 -unqiue number
.我将使用正则表达式来做到这一点。我发现这个 ([^\d])[0-9]{4}
可以找到任何四位数字,但我只希望它找到一个 4 位数字,如果它有 -
在它前面。我怎样才能做到这一点?
最佳答案
//Regular expression
$regex = "/-(\\d{4})\\.html/";
//String to check
$string = "http://www.example.co.uk/example-product-3436.html";
//Output match to $match
preg_match($regex, $string, $match);
//Print the unique number
echo $match[1];
正则表达式的解释:
/
是正则表达式的开始-
匹配连字符(...)
是一个捕获组(你想要返回的)\d
匹配任何数字 ([0-9]){4}
需要四个字符(\d{4}
需要四个字符)\.
匹配字符“.”从字面上看html
按字面匹配“html”/
标记正则表达式的结束
关于php - 如果旁边有 '-',正则表达式只会添加 4 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35405638/