需要有关正则表达式的帮助来解析此字符串

时间:2013-11-06 14:47:01

标签: php regex expression

我不清楚正则表达式。请从字符串中获取一些数据需要帮助,如果有人可以提供帮助,请。 当我在这里粘贴字符串时,它会格式化HTML,所以请检查pastebin链接。

好的,所以我需要的是来自这个字符串的每个字段数据,即“Pickup From:”,“Deliver To:”,“Special Instruction:”等。格式将保持不变,即每次休息都会只有内部数据才会改变。

例如:Pickup From:Washington,DC,USA

所以我只需回答“华盛顿特区,美国”。

Check Pastebin

有人可以帮忙吗?我正在使用php。

4 个答案:

答案 0 :(得分:1)

我认为你不需要正则表达式。使用explode()

$string = 'Pickup From: Washington, DC, USA';
$ar = explode(': ', $string);
if (count($ar) == 2) { # Want to check to make sure it's not empty!
   echo $ar[1]; # Echoes "Washington, DC, USA"
}

答案 1 :(得分:0)

您可能想要所有字段:

$in = '<a href="example.com/edit"> Edit Your Delivery Details  </a>Pickup From: Washington, DC, USA<br>Deliver To: WDG Architecture, Connecticut Avenue Northwest, Washington, D.C., DC<br>Special Instruction: Yes, order fast<br>Person Name: sdf<br>Person Contact: dfsdf<br>Person Email: sdfsdasd@asd.asd<br>Pickup Day: Today<br>Pickup Time: ASAP<br><br>';

$lines = explode("<br>", $in);
$matches = array();
foreach ($lines as $line) {
    if (strstr($line, ":")) {
        $matches[] = preg_split("/\s*:\s*/", $line, 2);
    }
}
print_r($matches);

给出:

Array
(
    [0] => Array
        (
            [0] =>  Edit Your Delivery Details  
Pickup From
            [1] => Washington, DC, USA
        )

    [1] => Array
        (
            [0] => Deliver To
            [1] => WDG Architecture, Connecticut Avenue Northwest, Washington, D.C., DC
        )

    [2] => Array
        (
            [0] => Special Instruction
            [1] => Yes, order fast
        )

    [3] => Array
        (
            [0] => Person Name
            [1] => sdf
        )

    [4] => Array
        (
            [0] => Person Contact
            [1] => dfsdf
        )

    [5] => Array
        (
            [0] => Person Email
            [1] => sdfsdasd@asd.asd
        )

    [6] => Array
        (
            [0] => Pickup Day
            [1] => Today
        )

    [7] => Array
        (
            [0] => Pickup Time
            [1] => ASAP
        )

)

正如你所看到的那样,它还不是很完美,但它可以帮助你。

使用strpos查找</a>并修剪。如果您有更多 noise ,那么您也需要修剪它。


对于投票的人:你能解释一下你的downvote吗?我错过了什么吗?

答案 2 :(得分:0)

考虑以下Regex ......

((?<=(Pickup\sFrom:)).*|(?<=(Deliver\sTo:)).*|(?<=(Special\sInstruction:)).*)

答案 3 :(得分:-1)

可以在没有正则表达式的情况下决定:

$test = "Pickup From: Washington, DC, USA";
$position = strrpos($test, ':');
$string = $test;
if ($position !== false)
    $string = substr($test, $position+1);
else
    $string = $test;

echo $string;

使用正则表达式:

$test = "Pickup From: Washington, DC, USA";
if (preg_match('/: ([^,]+, [A-Z]{2}, [A-Z]{3})$/', $test, $m) !== false)
    $string = $m[1];
else
    $string = $test;

print_r($string);