Checking for characters in PHP variable

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

Previous topic - Next topic

AliceFowell89Topic starter

Forum users, can you please advise me on how to determine if a variable, which has a certain value, contains a character other than a number? Which function would be suitable for this purpose?
  •  

organictextiles

To ensure that there are no characters other than numbers in an integer variable, you can use typecasting to convert it to a positive integer using (int) $x; as described in http://php.net/manual/en/language.types.type-juggling.php.

If you need to check for the presence of a number as stated in your question, take note that if the information is from a form, it will always be treated as a string and PHP may implicitly perform a type conversion unless otherwise specified. However, if the data is exchanged between scripts internally, different types could potentially be used.
  •  

MARK PETERSON

When it comes to finding the precise instance of a word, regular expressions can be more effective despite the faster speed of the strpos() and stripos() functions. These built-in PHP functions may present problems for accurately finding the exact occurrence of a word. In that case, regular expressions are the preferable choice.

To mark a word boundary in a regular expression template, you can use the "b" expression. This method allows the preg_match() function to locate exact matches, return FALSE for partial matches, and achieve more accurate results. 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]';
}
  •