Reputation: 2250
I want to extract the three pieces of information into an array, but it doesn't work for me.
$string = "<Name>Joh Doe <Email>[email protected] <App ID> 130105"
$var = preg_split("/^<.*<$/" , $string);
Upvotes: 0
Views: 175
Reputation: 101
$string = "<Name>Joh Doe <Email>[email protected] <App ID> 130105";
preg_match_all('/<([^>]*)>([^<]+)/' , $string, $matches);
var_dump($matches);
Gives:
array(3) {
[0] => array(3) {
[0] => string(14) "Joh Doe "
[1] => string(25) "[email protected] "
[2] => string(15) " 130105"
}
[1] => array(3) {
[0] => string(4) "Name"
[1] => string(5) "Email"
[2] => string(6) "App ID"
}
[2] => array(3) {
[0] => string(8) "Joh Doe "
[1] => string(18) "[email protected] "
[2] => string(7) " 130105"
}
}
Upvotes: 3
Reputation: 92976
Try this
$string = "<Name>Joh Doe <Email>[email protected] <App ID> 130105";
$var = preg_split("#\s*<.*?>\s*#" , $string);
print_r($var);
Outputs:
Array ( [0] => [1] => Joh Doe [2] => [email protected] [3] => 130105 )
The first index is empty because there is nothing before the first tag.
Update
As suggested by JRL
$var = preg_split("#\s*<.*?>\s*#" , $string, -1, PREG_SPLIT_NO_EMPTY);
output:
Array ( [0] => Joh Doe [1] => [email protected] [2] => 130105 )
Upvotes: 1
Reputation: 33908
You could use:
$string = "<Name>Joh Doe <Email>[email protected] <App ID> 130105";
preg_match_all('/>\s*([^<]+)/', $string, $var);
print_r($var[1]);
Output:
Array
(
[0] => Joh Doe
[1] => [email protected]
[2] => 130105
)
Upvotes: 2
Reputation: 91385
Don't anchor the regex in the split, also the regex doesn't end with <
but >
.
$str = "<Name>Joh Doe <Email>[email protected] <App ID> 130105";
$arr = preg_split("/<[^>]+>/" , $str);
print_r($arr);
output:
Array
(
[0] =>
[1] => Joh Doe
[2] => [email protected]
[3] => 130105
)
Upvotes: 2