简体   繁体   中英

PHP: Check if anything comes after given string in 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?

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)) {
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM