简体   繁体   English

PHP从文本中的字符串中提取子字符串

[英]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: 我有一个由许多字符串和每个字符串组成的文本,如果检查结果为true,我想得到一个具有某些属性的特定字符串:

  1. the string starts with a sign like "atm" 字符串以“atm”之类的符号开头
  2. after the sign there is a numeric part with a variable lenght 在符号后面有一个带有变量长度的数字部分

ie the word could be like atm123456 or atm7890 即这个词可能像atm123456或atm7890

Any help is appreciated, thanks. 任何帮助表示赞赏,谢谢。

Can you try this 你能试试吗?

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

You can use regular expression and preg_match() function 您可以使用正则表达式和preg_match()函数

$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 | PHP演示 | Regex demo 正则表达式演示

in case of multiple value or repeated items. 如果是多个值或重复的项目。 you can use preg_match_all like this 你可以像这样使用preg_match_all

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM