dpzff20644 2017-11-23 05:55
浏览 44
已采纳

PHP:检查URL中给定字符串后是否有任何内容?

I need to create a an if statement that fires if there is something after a given string in the URL.

For example, if my string is 'Honda' I need to check if something appears after that word in the url, eg something like:

$brand = "honda";

if (url contains $brand . '/*'){
  // Do something.
}

Example urls could be:

  • mysite.com/honda (which would fail the above)
  • mysite.com/cars/honda (which would fail the above)
  • mysite.com/honda/civic (which would pass the above)
  • mysite.com/honda/accord (which would pass the above)

I know I can use strpos() to detect if the string is within the URL, but how can I detect if anything comes after that?

  • 写回答

1条回答 默认 最新

  • doutu1889 2017-11-23 05:58
    关注

    Use a regular expression that looks for the $brand at the end of the string.

    if (! preg_match("/{$brand}$/", $url)) {
        // ...
    }
    

    If you need to check if the $brand actually appears in the URL before running your end of string check:

    if (strpos($brand, $url) !== false && ! preg_match("/{$brand}$/", $url)) {
        // ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办