3

Possible Duplicate:
How do I find the index of a regex match in a string?
How to get the position of a Regex match in a string?

Given the following strings, how can I find the position of the first alpha in each string?

1) - Alpha

2) beta

3) . Gamma

4) 'delta'

Ultimately I'm after the substring, starting at the first alpha character. So I'm looking to offset my substring to get Alpha.

The offsets I'm looking for (from the above examples) are:

1) 2

2) 0

3) 2

4) 1

I'm not concerned with any special characters. Just the first alpha, case insensitive (A-Za-z).

Community
  • 1
  • 1
Ryan
  • 14,682
  • 32
  • 106
  • 179

2 Answers2

6

Use preg_match() :

Code:

foreach (array('- Alpha', 'beta', '. Gamma', "'delta'") as $value) {
    preg_match('~[a-z]~i', $value, $match, PREG_OFFSET_CAPTURE);
    print_r($match);
}

Output:

Array
(
    [0] => Array
        (
            [0] => A
            [1] => 2
        )
)
Array
(
    [0] => Array
        (
            [0] => b
            [1] => 0
        )
)
Array
(
    [0] => Array
        (
            [0] => G
            [1] => 2
        )
)
Array
(
    [0] => Array
        (
            [0] => d
            [1] => 1
        )
)
Glavić
  • 42,781
  • 13
  • 77
  • 107
0

Use a for loop and add if condition inside,Run the for loop across entire string and 'i' is the character at the current position

if(i>='a' && i<='z' || i>='A' && i<='Z')
harry4
  • 189
  • 1
  • 4
  • 16