0

I have a website connected to a web service and I need to recognize the characters received in my codes.

For instance, I receive a message like this :

$str = "Hello Europe";
or :
$str = "4 times !";
or :
$str = "452231";
or :
$str= "*Majid SH";
or ...

I want my code to understand the character which my message started by, and do the a function correspond to a special character.

For example, if it was started by a string, do function num1, or if it was started by '.' [dot], do function num2.

Thank you for helping me.

Kyle
  • 2,822
  • 2
  • 19
  • 24
Majid Sh
  • 1
  • 2

4 Answers4

1

You can use substr() as follows:

Code:

$char1 = substr($str, 0, 1); //getting first character

if(is_numeric($char1){
    //execute num1()
    num1();
}
elseif ($char1 == '.') {
    //execute num1()
    num2();
}
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

You should use the switch If you want to find out if the character is a specific thing like a comma or period. Also understand that Strings can simply be thought of as Char arrays so you can simply call $str[0] to get the first char (See here.)

switch ($str[0]) {
   case ",":
      num1();
      break;
   case ".": 
      num2();
      break;
}

You can keep making different cases to handle different situations. Just make sure you include a break between each case.

If you want to check if something is a string I believe there is an is_string but for that you may need to use substr as many other people have recommended because $str[0] I believe returns a char and not a string so it won't verify. The switch statement simply checks if the parameter is the same as the case using loose comparison. If you want more advanced checking, you'll probably need to use your own if statement to check or even regex. Hope this helps.

Community
  • 1
  • 1
aug
  • 11,138
  • 9
  • 72
  • 93
0

I would use strpos()

<?php
$StringFromService;
$str = "Hello Europe";
$Search = strpos($StringFromService;, $str);

if ($Search === true) {
    // run function
} 
?>
Kevin Lynch
  • 24,427
  • 3
  • 36
  • 37
-1
$str = 'value'; // value
$firstChar = substr($str, 0, 1);

if (is_numeric($firstChar)) {
    // do something numeric'
} else if ($firstChar === '.') {
    // do something dot'
} else {
    // do something string'
}
UrGuardian4ngel
  • 568
  • 2
  • 7