I have some strings which can be in the following format
我有一些字符串,可以采用以下格式
sometext moretext 01 text text sometext moretext 002 text text 1 (somemoretext) etc
I want to split these strings into following: text before the number and the number
我想将这些字符串拆分为以下内容:数字和数字之前的文本
For example: text text 1 (somemoretext)
When split will output:
text = text text
number = 1
Anything after the number can be discarded
例如:文本文本1(somemoretext)当分割将输出:text = text text number = 1数字后面的任何内容都可以丢弃
Have read up about using regular expressions and maybe using preg_match or preg_split but am lost when it comes to the regular expression part
已经阅读了有关使用正则表达式的信息,并且可能使用preg_match或preg_split,但在正则表达式部分时却丢失了
2 个解决方案
#1
12
preg_match('/[^\d]+/', $string, $textMatch);
preg_match('/\d+/', $string, $numMatch);
$text = $textMatch[0];
$num = $numMatch[0];
Alternatively, you can use preg_match_all
with capture groups to do it all in one shot:
或者,您可以将preg_match_all与捕获组一起使用,一次完成所有操作:
preg_match_all('/^([^\d]+)(\d+)/', $string, $match);
$text = $match[1][0];
$num = $match[2][0];
#2
1
Use preg_match_all() + if you wish to match every line use m modifier:
如果你想匹配每一行使用m修饰符,请使用preg_match_all()+:
$string = 'sometext moretext 01 text
text sometext moretext 002
text text 1 (somemoretext)
etc';
preg_match_all('~^(.*?)(\d+)~m', $string, $matches);
All your results are in $matches
array, which looks like this:
你的所有结果都在$ matches数组中,如下所示:
Array
(
[0] => Array
(
[0] => sometext moretext 01
[1] => text sometext moretext 002
[2] => text text 1
)
[1] => Array
(
[0] => sometext moretext
[1] => text sometext moretext
[2] => text text
)
[2] => Array
(
[0] => 01
[1] => 002
[2] => 1
)
)
Output example:
foreach ($matches[1] as $k => $text) {
$int = $matches[2][$k];
echo "$text => $int\n";
}
#1
12
preg_match('/[^\d]+/', $string, $textMatch);
preg_match('/\d+/', $string, $numMatch);
$text = $textMatch[0];
$num = $numMatch[0];
Alternatively, you can use preg_match_all
with capture groups to do it all in one shot:
或者,您可以将preg_match_all与捕获组一起使用,一次完成所有操作:
preg_match_all('/^([^\d]+)(\d+)/', $string, $match);
$text = $match[1][0];
$num = $match[2][0];
#2
1
Use preg_match_all() + if you wish to match every line use m modifier:
如果你想匹配每一行使用m修饰符,请使用preg_match_all()+:
$string = 'sometext moretext 01 text
text sometext moretext 002
text text 1 (somemoretext)
etc';
preg_match_all('~^(.*?)(\d+)~m', $string, $matches);
All your results are in $matches
array, which looks like this:
你的所有结果都在$ matches数组中,如下所示:
Array
(
[0] => Array
(
[0] => sometext moretext 01
[1] => text sometext moretext 002
[2] => text text 1
)
[1] => Array
(
[0] => sometext moretext
[1] => text sometext moretext
[2] => text text
)
[2] => Array
(
[0] => 01
[1] => 002
[2] => 1
)
)
Output example:
foreach ($matches[1] as $k => $text) {
$int = $matches[2][$k];
echo "$text => $int\n";
}