php - Getting values after a specific character and stopping on other specific characters regex
Get the solution ↓↓↓I am trying to get values after a specific charachter and stopping on other specific charchters. This is what I tried
$whois = 'Registrant Name: Domain Administrator Registrant Organization: Yahoo! Inc. Registrant Street: 701 First Avenue Registrant City: Sunnyvale';
$data = preg_match_all('/:\s(.*?)\s/', $whois, $data_whois);
var_dump($data_whois[1]);
The whois is for yahoo: http://whois.domaintools.com/yahoo.com
CURRENT OUTPUT
1 => string 'Domain' (length=6)
2 => string 'Yahoo!' (length=6)
3 => string '701' (length=3)
4 => string 'Sunnyvale' (length=9)
EXPECTED OUTPUT
1 => string 'Domain Administrator' (length=6)
2 => string 'Yahoo! Inc.' (length=6)
3 => string '701 First Avenue' (length=3)
4 => string 'Sunnyvale' (length=9)
But it's taking only the first word. I believe that is because(.*?)\s
I also tried(.*?\s.*?)\s
and it's taking the second word, but if the value doesn't have a second word is going to take the wordRegistrant
so I kind of need to stop on Registrant but don't understand exactly how.
Answer
Solution:
Since you are using a lazy quantifier.*?
followed by a\s
the match will stop at the first whitespace character.
A way to solve the problem is to use the fact that.*?
must be followed by a space and the word "Registrant" or the end of the string:
/:\s(.*?)(?:\sRegistrant\b|\s*$)/
An other possible way is to usepreg_split
:
$str = 'Registrant Name: Domain Administrator Registrant Organization: Yahoo! Inc. Registrant Street: 701 First Avenue Registrant City: Sunnyvale';
$pattern = '~\s*\bRegistrant[^:]+:\s*~';
$result = preg_split($pattern, $str, -1, PREG_SPLIT_NO_EMPTY);
Answer
Solution:
It seems like your fields has exactly two words followed by:
on the second word. If yes then you may try the below regex.
: \K.*?(?= \S+ \S+:|$)
PHP code would be,
<?php
$data = 'Registrant Name: Domain Administrator Registrant Organization: Yahoo! Inc. Registrant Street: 701 First Avenue Registrant City: Sunnyvale';
$regex = '~: \K.*?(?= \S+ \S+:|$)~';
preg_match_all($regex, $data, $matches);
print_r($matches);
?>
Output:
Array
(
[0] => Array
(
[0] => Domain Administrator
[1] => Yahoo! Inc.
[2] => 701 First Avenue
[3] => Sunnyvale
)
)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: your lock file does not contain a compatible set of packages. please run composer update.
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.