[英]Parse a formatted string with multiple delimiters into an associative array
I am using a module to create booking orders in my website.我正在使用一个模块在我的网站上创建预订订单。
They have a hook I can use which fires after a new booking is created.他们有一个钩子,我可以使用它在创建新预订后触发。
The variable I get is booking_form: Inside this variable is the following:我得到的变量是booking_form:在这个变量里面是这样的:
text^name1^PETER~text^secondname1^SMITH~text^phone1^023482348~text^adres1^STREETAVENUE 1B~text^postcode1^91201CA~text^woonplaats1^LIVINGPLACE~email^email1^peter@example.com
Is there someway in PHP to get all the values of all the fields in an array or something? PHP 中是否有某种方法可以获取数组中所有字段的所有值? So something like this?所以像这样的事情?
array(
name or name1? => PETER,
secondname => SMITH,
etc... => etc...
)
So the function has to split the string based on the ^ and ~ characters.因此该函数必须根据 ^ 和 ~ 字符拆分字符串。
Try this :尝试这个 :
$result = array();
$data = explode ( "~", $yourString )
foreach ( $data as $element)
{
$elt = explode ( "^", $element ) ;
$result[$elt[1]] = $elt[2];
}
Another way to do this...另一种方法来做到这一点......
$input = 'text^name1^PETER~text^secondname1^SMITH~text^phone1^023482348~text^adres1^STREETAVENUE 1B~text^postcode1^91201CA~text^woonplaats1^LIVINGPLACE~email^email1^peter@example.com';
$split = explode('~', $input);
$finalArray = [];
foreach($split as $thing) {
list ($type, $key, $value) = explode('^', $thing);
$finalArray[$key] = $value;
}
print_r($finalArray);
Your formatted string seems inconsistently formatted and I don't understand the relevance of the text
and email
markers.您的格式化字符串的格式似乎不一致,我不明白text
和email
标记的相关性。
Furthermore, we don't know your input data may vary because you only gave us one and string AND we don't know your exact desired output because you "yatta-yatta"ed what you expect.此外,我们不知道您的输入数据可能会有所不同,因为您只给了我们一个和字符串,而且我们不知道您确切想要的输出,因为您“yatta-yatta”符合您的期望。
That said, parsing the string can be done with regex.也就是说,可以使用正则表达式来解析字符串。
$string = 'text^name1^PETER~text^secondname1^SMITH~text^phone1^023482348~text^adres1^STREETAVENUE 1B~text^postcode1^91201CA~text^woonplaats1^LIVINGPLACE~email^email1^peter@example.com';
preg_match_all('/(?:text|email)\^([^^]+)\^([^^~]*)/', $string, $matches, PREG_SET_ORDER);
var_export(
array_column($matches, 2, 1)
);
Output:输出:
array (
'name1' => 'PETER',
'secondname1' => 'SMITH',
'phone1' => '023482348',
'adres1' => 'STREETAVENUE 1B',
'postcode1' => '91201CA',
'woonplaats1' => 'LIVINGPLACE',
'email1' => 'peter@example.com',
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.