I have a string and I need to check it for several characters. I can do that with strpos();
. But in this case, I would need to use strpose();
several times. something like this:
$str = 'this is a test';
if(
strpos($str, "-") === false &&
strpos($str, "_") === false &&
strpos($str, "@") === false &&
strpos($str, "/") === false &&
strpos($str, "'") === false &&
strpos($str, "]") === false &&
strpos($str, "[") === false &&
strpos($str, "#") === false &&
strpos($str, "&") === false &&
strpos($str, "*") === false &&
strpos($str, "^") === false &&
strpos($str, "!") === false &&
strpos($str, "?") === false &&
strpos($str, "{") === false &&
strpos($str, "}") === false
)
{ do stuff }
Now I want to know, is it possible to use a regex
to define my condition summary?
Edit: here is some examples:
$str = 'foo' ----I want this output---> true
$str = 'foo!' -------------------------> false
$str = '}foo' -------------------------> false
$str = 'foo*bar' -------------------------> false
and so on. In other word, I want just text character: abcdefghi...
.
You could use a basic regex:
$unwantedChars = ['a', '{', '}'];
$testString = '{a}sdf';
if(preg_match('/[' . preg_quote(implode(',', $unwantedChars)) . ']+/', $testString)) {
print "Contains invalid characters!";
} else {
print "OK";
}
Use negative lookahead assertion.
if (preg_match("~^(?!.*?[-_^?}{\]\[/'@*&#])~", $str) ){
// do stuff
}
This will do the stuff inside braces only if the string won't contain anyone of the mentioned characters.
If you want the string to contain only word chars and spaces.
if (preg_match("~^[\w\h]+$~", $str)){
// do stuff
}
or
AS @Reizer metioned,
if(preg_match("~^[^_@/'\]\[#&*^!?}{-]*$~", $str)){
Replace the *
(present next to the character class) in the above with +
, if you don't want to match an empty string.
For only alphabets and spaces.
if(preg_match("~^[a-z\h]+$~i", $str) ){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With