Luke
Luke

Reputation: 513

PHP extract substring from strings in text

I'have a text composed of many strings and for each string, if the check is true, I would like to get a specific one having some attributes:

  1. the string starts with a sign like "atm"
  2. after the sign there is a numeric part with a variable lenght

i.e. the word could be like atm123456 or atm7890

Any help is appreciated, thanks.

Upvotes: 1

Views: 2452

Answers (3)

hex494D49
hex494D49

Reputation: 9235

You can use regular expression and preg_match() function

$string = "atm123456";
$pattern = "(atm\d+)";
preg_match($pattern, $string, $matches); // you may use preg_match_all() as well
print_r($matches);

Output:

Array
(
    [0] => atm123456
)

PHP demo | Regex demo

Upvotes: 1

Ram Sharma
Ram Sharma

Reputation: 8809

in case of multiple value or repeated items. you can use preg_match_all like this

$string = "atm123456 with atm7890 items";
$pattern = "(atm\d+)";
preg_match_all($pattern, $string, $matches);
print_r($matches);

Upvotes: 1

Punitha Subramani
Punitha Subramani

Reputation: 1477

Can you try this

    $thestring='atm123456';
    $thestrToEx = explode(' ',$thestring );
    $thestrToExArr=array_walk($thestrToEx,'intval');
    $theValues=explode($thestrToExArr,$thestring);
    echo $thestrToExArr.$theValues[1];

Upvotes: 1

Related Questions