0

I have one string like below

$string = "1234@#$ABCFG3478&*";

Now I want first character from this string that is not numeric or special character, It should be only A-a to Z-z.

Means, I need only "A" from this string.

I have try this formula:

 substr($string, 1);
2
  • 1
    The dollar sign in your string will give a notice (undefined variable) you should change your double quotes to single quotes to avoid it. Commented Mar 24, 2015 at 15:14
  • @jigsVirani if you're happy with my answer below, you can accept it. Commented Mar 25, 2015 at 13:11

2 Answers 2

4

Use regex:

$string = '1234@#$ABCFG3478&*';

if (preg_match('/[a-z]/i', $string, $match)) {
    $firstLetter = $match[0];
} else {
    // there's no letters in given string
}
Sign up to request clarification or add additional context in comments.

1 Comment

I suggest you incorporate @Daan's advice into your answer because otherwise your good solution won't work.
1

This should work for you:

(Here I just replace every character with preg_replace() which isn't in the range a-zA-Z with an empty string and then I just grab the first letter)

$string = '1234@#$ABCFG3478&*';
echo preg_replace("/[^a-zA-Z]/", "", $string)[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.