2

How I can check if some string contains forward slash in PHP?

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

4

It is very simple:

preg_match ('~/~', $string);

2 Comments

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.
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.