Home > database >  Get the characters before the first letter from the string on PHP
Get the characters before the first letter from the string on PHP

Time:02-04

I have a string like

"   1232  - avff"

and I need to extract the part before the first letter, which happens to be "a" in this example. It can be any upper or lower case letter. Since the letter or previous part is unknown, I can't use PHP functions like strpos, or explode. I think I need to use regex, but I don't understand it at all. So I hope someone can help me on this.

CodePudding user response:

You could use a regex replacement approach here:

$input = "   1232  - avff";
$output = preg_replace("/[a-z].*$/", "", $input);
echo $output;  //     1232. - 

The regex pattern [a-z].*$ will match from the first lowercase letter until the end of the string. We strip off this match by replacing with empty string, leaving behind the substring you actually want.

  •  Tags:  
  • Related