I'm a self-thought PHP beginner and I'm still learning regular expressions. Here is a problem i encountered with preg_match_all
and arrays
my array has exactly the following information:
;;CARLOS||ANDREW||STEPH||SUE||JUDY||HAROLD||JAMES||KATIE||JESSICA;;
What i'm trying to do is display each name individually there are about 250 different names, the array always begins with ;; and always ends with ;; so here is my issue, first my array loads fine but only the first name by doing:
preg_match_all('/^(.+?)\|\|/', $body, $part);
foreach ($part[1] as $part){
print_r($part);
Result is ;;CARLOS
Where $body
is the huge list of names (array with 250+ names).
Desired result:
CARLOS
ANDREW
STEPH
JUDY
HAROLD
JAMES
KATIE
JESSICA
Please understand i cannot change the input array, it is what it is. So basically on the first array i have load the entire list then i need to break it by | characters.
Thanks for any advice.
No need to use regular expressions here. explode
and trim
will work just fine.
$str = trim($body, ";"); // Remove semi-colons
$arr = explode("||", $str); // Return array of strings delimited by double pipes
print_r($arr);
Output
Array
(
[0] => CARLOS
[1] => ANDREW
[2] => STEPH
[3] => SUE
[4] => JUDY
[5] => HAROLD
[6] => JAMES
[7] => KATIE
[8] => JESSICA
)
If you want your desired result exactly, then implode
the above output.
echo implode(" ", $arr);
// Outputs: CARLOS ANDREW STEPH SUE JUDY HAROLD JAMES KATIE JESSICA
$list = explode('||',trim($list,';'));
;;CARLOS||
is the smallest match available, which is exactly what you're asking the regex engine to do. Try this regular expression:
preg_match_all('/(?<=\|\||;;)(.+?)(?=\|\||;;)/', $body, $part);
print_r($part[1]);
I would use explode()
instead.
<?php
$string=";;CARLOS||ANDREW||STEPH||SUE||JUDY||HAROLD||JAMES||KATIE||JESSICA;;";
$names=explode("||", substr($string,2,strlen($string)-4));
print_r($names);
gives us:
Array
(
[0] => CARLOS
[1] => ANDREW
[2] => STEPH
[3] => SUE
[4] => JUDY
[5] => HAROLD
[6] => JAMES
[7] => KATIE
[8] => JESSICA
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.