如何创建正确的preg_replace模式?

时间:2017-05-15 12:50:03

标签: php preg-replace preg-match

我在magento商店有这些网址: charogh /产品/ 1298 /产品名 每个产品的产品名称都会更改,正确的结构是: charogh / product / [0-9] + / [a-zA-z0-9] +

我应该更改并更换产品/ [0-9] + /'与''并将网址设为charogh /'当用户输入此网址时 ' charogh /产品/ [0-9] + /' 用户输入此URL时不要替换它 ' charogh /产品/ [0-9] + /产品名' 我怎样才能使用preg_replace或preg_match?

我使用这种模式,但它取代了两种结构 $头= preg_replace函数(' // charogh /产品/ [0-9] + /'" charogh",$报头);

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我建议您使用$锚点

来锚定字符串末尾的匹配项
'/\/charogh\/product\/[0-9]+\/?$/'

这样,您将阻止匹配包含1位以上数据的字符串。

此外,最后的\/?允许匹配1或0 /个符号(即/是可选的。)