Checking for characters in a PHP variable

Started by AliceFowell89, Jul 20, 2022, 09:51 AM

Previous topic - Next topic

AliceFowell89Topic starter

Forum users, please tell me:
There is a variable that passes a certain number... With which function can I check if the variable contains a letter or any character, except a number?
  •  

organictextiles

http://php.net/manual/en/function.is-numeric.php

If it's an integer and you need to be sure that there will be nothing besides the number - then use typecasting to a positive integer through (int) $x;
http://php.net/manual/en/language.types.type-juggling.php

It seems that within the question you have formulated, it is necessary to check for the presence of a number.
There is a nuance - if this is info from a form, then it will always be a string and PHP, if not specified otherwise, will perform an implicit type conversion.
If this is internal data between scripts, then different types could be used.
  •  

MARK PETERSON

Using regular expressions to find the exact occurrence of a word:
The strpos() and stripos() functions work faster than regular expressions. But using them to find the exact occurrence of a word can be problematic.
In such situations, it is better to use regular expressions.
You can use expression b in a regular expression template to mark a word boundary. If the word you are looking for is enclosed in expressions b, the preg_match() function will find only exact occurrences of the word and return FALSE for partial matches. Here is an example:

$the_string = 'Photosynthesis and risky are long words.';
$the_word = 'synthesis';

// Output - The word "synthesis" has an exact match in the given string. [FALSE positive]
if (preg_match('/synthesis/', $the_string)) {
  echo 'The word 'synthesis' has an exact match on this line. [FALSE positive]';
}

// Output - The word "synthesis" has an exact match in the given string. [FALSE positive]
if (strpos($the_string, $the_word)) {
  echo 'The word 'synthesis' has an exact match on this line. [FALSE positive]';
}

// Output - The word "synthesis" does not have an exact match in this string. [Expected Result]
if (preg_match('/bsynthesisb/', $the_string)) {
  echo 'The word 'synthesis' has an exact match on this line. [FALSE positive]';
} else {
  echo 'The word 'synthesis' does not have an exact match in this string. [Expected Result]';
}
  •