如何在foreach循环中将字符串与PHP中的preg_split匹配

问题描述 投票:2回答:2

我使用此分隔符|有两部分的数据

$data = 'hello | Hello there
price | Lets talk about our support.
how are you ?| Im fine ';

我的静态单词是$word= 'price'

我的代码

 $msg = array_filter(array_map('trim', explode("\n", $data)));
 foreach ($msg as $singleLine) {
            $partition = preg_split("/[|]+/", trim($singleLine), '2');
            $part1 = strtolower($partition[0]);

            }

我如何匹配数据?我需要这样的结果:Let's talk about our support

php regex preg-match preg-match-all
2个回答
1
投票

您可以使用单个正则表达式方法:

'~^\h*price\h*\|\h*\K.*\S~m'

请参见regex demo

详细信息

  • [^-一行的开始(由于[C​​0]修饰符)]
  • [m-0+水平空格
  • [\h*-您的静态单词
  • [price-\h*\|\h*包含0+水平空白]
  • [|-匹配重置运算符,它丢弃到目前为止匹配的文本]
  • [\K-0+个除换行符以外的字符,尽可能多,直到行中最后一个非空白字符(包括它)。]]
  • .*\S

PHP code

1
投票

Wiktor的答案似乎不错,但是您可能希望将数据转换为if (preg_match('~^\h*' . preg_quote($word, '~') . '\h*\|\h*\K.*\S~m', $data, $match)) { echo $match[0]; } 数组。

© www.soinside.com 2019 - 2024. All rights reserved.