rocklobster
rocklobster

Reputation: 619

PHP get start and end positions of substring containing specific characters

I'm doing some string processing and would like to know how I can obtain the start and end indexes of a substring that contains certain characters or criteria.

For example:

I have a string:

"hello this is MY_EXAMPLE_STRING"

I'd like to be able to find the start and end index of MY_EXAMPLE_STRING

The function prototype might look like this:

$string = "hello this is MY_EXAMPLE_STRING";
$capitals = true;
$myArray = findIndices($string, $capitals, '_');

So it will return matching start and end indexes of any substring that has capitals and underscores.

Perhaps Regex is the best for this? If I was searching for as substring with capitals and underscores?

EDIT:

Edited my question for clarity.

Upvotes: 1

Views: 2687

Answers (1)

ilpaijin
ilpaijin

Reputation: 3695

Yes, I think Regex is the best choice, something this way:

$string = "hello this is MY_EXAMPLE_STRING";
$pattern = "/[A-Z]/";

preg_match($pattern,$string,$match,PREG_OFFSET_CAPTURE);

$index = $match[0][1];
$substring = substr($string, $index);

echo 'start at '.$index;
var_dump($substring);
echo 'end at '. ($index + strlen($substring));

Or could be something like this in case of multiple occurrence:

$string = "this is MY_STRING and ANOTHER_STRING";
$pattern = "/[A-Z|_]+/";

preg_match_all($pattern,$string,$match,PREG_OFFSET_CAPTURE);

foreach($match[0] AS $k => $m )
{
    $index = $m[1];
    $substring = $m[0];

    echo 'Start at '.$index;
    var_dump($substring);
    echo 'End at '. ($index + strlen($substring)) . '<br />';
}

Upvotes: 1

Related Questions