How I can check if some string contains forward slash in PHP?
2 Answers
Check for occurences with strpos()
if (strpos($string, '/') !== FALSE) // Found
Returns the position as an integer. If needle is not found, strpos() will return boolean FALSE.
This is faster than a regular expression, and most other methods, because it stops checking at the first occurrence.
Comments
It is very simple:
preg_match ('~/~', $string);
2 Comments
Phil
From the manual: Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.
Jakob Egger
Using
preg_match has the advantage of being easier to understand than the weird strpos!==false code. As long as your critical path doesn't include checking a million strings whether they contain a string, I'm pretty sure preg_match is fine. It's also easier to refactor if eg. you decide you only want to match trailing slashes...