regex - How to match String in foreach loop with preg_split in PHP
Get the solution ↓↓↓I have data with 2 parts with this separator
$data = 'hello Hello there
price Lets talk about our support.
how are you ? Im fine ';
And my static word is$word= 'price'
My code
$msg = array_filter(array_map('trim', explode("\n", $data)));
foreach ($msg as $singleLine) {
$partition = preg_split("/[]+/", trim($singleLine), '2');
$part1 = strtolower($partition[0]);
}
How can I match the data? I need the result to be like this:Let's talk about our support
Answer
Solution:
You may use a single regex approach:
'~^\h*price\h*\|\h*\K.*\S~m'
See the regex demo
Details
^
- start of a line (due tom
modifier)\h*
- 0+ horizontal whitespaceprice
- your static word\h*\\h*
-enclosed with 0+ horizontal whitespaces
|\K
- match reset operator that discards the text matched so far.*\S
- 0+ chars other than line break chars, as many as possible, up to the last non-whitespace char on the line (including it).
if (preg_match('~^\h*' . preg_quote($word, '~') . '\h*\\h*|\K.*\S~m', $data, $match)) {
echo $match[0];
}
Answer
Solution:
Wiktor's answer seems good, but you might want to turn your data into akey -> value
array.
If that is the case, you may do this:
$avp = [];
if (preg_match_all('/^ \h* (?<key>[^|]+?) \h* \| \h* (?<value>[^$]+?) \h* $/mx', $data, $matches, PREG_SET_ORDER)) {
foreach ($matches as [, $key, $value]) {
$avp[$key] = $value;
}
}
$word = 'price';
echo $avp[$word]; // Lets talk about our support.
Demo: https://3v4l.org/uMBAg
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: to enable extensions, verify that they are enabled in your .ini files
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.