如何抓住第一行字符串并在php中显示?

时间:2016-02-24 12:13:49

标签: php

以下是我的代码:

<?php 
 $array = explode("\n", $order['payment_address']);
 $firstLine = $array[0];
 echo $firstLine;
 ?>

我想要做的是从$ order [&#39; payment_address&#39;]中获取第一行中的客户名称并打印出来。 Payment_address包括几行客户名称。试过Ben Pearl Kahan的代码,输出现在是 -

鲍勃史密斯 12

第1行:Bob Smith 12 2号线:Kannaught Place 德里282010 北方邦 印度

虽然我只想要&#34; Bob Smith&#34;。

我是新手。 Plz帮助。

2 个答案:

答案 0 :(得分:0)

如果不提供$order["payment_address"]的输出,这应该会有所帮助:

//Trim whitespace from start/end of string
$pa = trim($order["payment_address"]);

//Check if the value is empty
if(!empty($pa)){

    //Explode by line
    $array = explode("\n", $pa);

    //Echo out first line
    echo "First line: {$array[0]}<br><br>";

    //See data line-by-line
    $num = 0;
    foreach($array as $line){
        $num++;
        echo "Line $num: $line<br>";
    }        

} else echo "Payment address is empty!<br>"; //Output error if $pa is empty

以逗号分隔的值:

//Trim whitespace from start/end of string
$pa = trim($order["payment_address"]);

//Check if the value is empty
if(!empty($pa)){

    //Explode by line
    $array = explode(", ", $pa);

    //Echo out first line
    echo "First line: {$array[0]}<br><br>";

    //See data line-by-line
    $num = 0;
    foreach($array as $line){
        $num++;
        echo "Line $num: $line<br>";
    }        

} else echo "Payment address is empty!<br>"; //Output error if $pa is empty

答案 1 :(得分:0)

如果您不确定变量中的内容,请始终var_dump()。在浏览器中查看

echo '<pre>'; var_dump($order['payment_address']); echo '</pre>';

以下regex would split在任何换行符序列或<br>并返回第一个非空项目。

$firstLine = preg_split('~<br */?>|\R~i', $order['payment_address'], -1, PREG_SPLIT_NO_EMPTY)[0];

See demo at eval.in