Lock
Lock

Reputation: 5522

Find position of first letter in string

How would I find the position of the first occurance of a letter (a-z) case insensitive using regex?

$string = "(232) ABC";

I want to see the number 7 returned as A is in position 7

I have found the following but it doesn't seem to work for all string:

preg_match("/^[a-z]+$/i", strtolower($tel_current), $matches, PREG_OFFSET_CAPTURE);

E.g. it doesn't work for the following:

"(520) 626-1855 kafds r";

I just get an empty array.

Upvotes: 0

Views: 1502

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You mean this?

<?php
preg_match('/[a-z]+/i', '|Tel: (520) 626-1855 kafds r', $matches, PREG_OFFSET_CAPTURE);
var_export($matches);
?>

Output:

array (
  0 => 
  array (
    0 => 'Tel',
    1 => 1,
  ),
)

To find the position of the string kafds r,

<?php
preg_match('/(?<=\d )\w+ \w+/i', '|Tel: (520) 626-1855 kafds r', $matches, PREG_OFFSET_CAPTURE);
var_export($matches);
?>

Output:

array (
  0 => 
  array (
    0 => 'kafds r',
    1 => 21,
  ),
)

Upvotes: 5

Related Questions