简体   繁体   English

如何在php中处理字符串

[英]How to process string in php

I have string like this 我有这样的字符串

$str="absdbsasd k=12312 sdasd l=89879 m=ken asddq casdasd"

and the output should be like this 输出应该是这样的

the question is how to process the string on variable $str to get output which is like this 问题是如何处理变量$ str上的字符串以获得类似这样的输出

k=12312
l=89879
m=ken asddq casdasd

I have tried to implement parse_str after I replace the space character (' ') into '&', but the output still got the wrong answer 在将空格字符('')替换为'&'之后,我尝试实现parse_str,但是输出仍然得到错误的答案

k=12312
l=89879
m=ken

Could anybody help me.. 有人可以帮我吗..

Assuming the logic is that identifiers are word chars ending with a = and values ends when the next identifier comes, but if the value starts with numbers then only the first word of numbers needed for the value, i would go about it like this: 假设逻辑是,标识符是与结束字字符=并且当所述下一个标识符来值结束,但如果该值以数字开头则仅所需的值号的第一个字,我会去这样的:

$str="absdbsasd k=12312 sdasd l=89879 m=ken asddq casdasd";

$parts = preg_split('/(\w+=)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);

$result = array();
$prev_was_an_identifier = false;
$last_identifier = null;
foreach ($parts as $part) {
    if ($prev_was_an_identifier) {
        if (preg_match('/^\d+/', $part)) {
            $result[$last_identifier] = preg_replace('/^(\d+).*/', '$1', $part);
        } else {
            $result[$last_identifier] = $part;
        }   
        $prev_was_an_identifier = false;
    } elseif (preg_match('/=$/', $part)) {
        $prev_was_an_identifier = true;
        $last_identifier = mb_substr($part, 0, -1);
    }
}

outputs: 输出:

array (
  'k' => '12312',
  'l' => '89879',
  'm' => 'ken asddq casdasd',
)

Well, first you need to define the structure of the string something like this: 好吧,首先,您需要定义字符串的结构,如下所示:

$str = "$first_value k=$secound_value l=$third_value m=$forth_value";

If the structure is as I have written, then It's pretty impossible to get what you need, since there are no sepperators or any other types of way to determine where one value ends and another value begins. 如果结构是我所写的,那么就几乎无法获得所需的内容,因为没有分隔符或任何其他类型的方法可以确定一个值在哪里结束而另一个值在哪里开始。 Look at this example: 看这个例子:

$str="absdbsasd k=12312 sdasd l=s l=8987 l=s 9 m=ken asddq casdasd"

There is no way to teel where the real l= starts. 没有办法在真正的l=开始的地方发呆。

If you would add some seperators like ' ( and make sure they don't appear in the values, the you can get something like this: 如果您要添加一些分隔符,例如' (,并确保它们未出现在值中,则可以得到如下内容:

$str="'absdbsasd' k='12312 sdasd l=s' l='8987 l=s 9' m='ken asddq casdasd'"

And then you can do a preg_match or preg_split check and get your desired values. 然后,您可以执行preg_matchpreg_split检查并获得所需的值。

Or, suggested, just make an array in the 1st place. 或者,建议将数组放在第一位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM