【问题标题】:php explode only pre delimiter and ignore restphp只爆炸预分隔符并忽略其余部分
【发布时间】:2013-05-24 19:03:03
【问题描述】:

是否可以只分解文本预分隔符(在 -- 之前),而忽略整个字符串的每一行的分隔符之后的所有内容。

例如:

string one -- string two
string three -- string four
string five -- string six

我只想爆炸一串三串和五串而忽略二串四六串。

谢谢

【问题讨论】:

  • 谢谢,太有帮助了...需要详细说明吗?
  • 你只需要explode()他们,而不是使用第二个组件。你可以use list() for that. 就像list($firstpart,) = explode(" -- ", $fullstring);
  • @MichaelBerkowski 这比 imo 迄今为止的任何答案都要好。当简单的工具可以工作时,不要写一些花哨的东西

标签: php explode


【解决方案1】:

你可以试试:

echo implode(",", array_map(function ($v) {
    return current(explode("--", $v));
}, explode("\n", $string)));

View Output

string one ,string three ,string five 

【讨论】:

  • 性感,爸爸。非常性感(比 foreach 更可取)。
  • 谢谢大家..我很感激。
  • $array = array_map(function ($v) { return current(explode("--", $v)); }, explode("\n", $string)); 就是你所需要的
【解决方案2】:

这将是一个多步骤的过程。

  • 首先按新行展开
  • 其次,循环遍历线条并以'--'展开
  • 第三,输出第一个匹配项。

PHP 示例

$Param = <<<LONG
string one -- string two
string three -- string four
string five -- string six
LONG;

$Lines = explode("\n", $Param);

$Output = [];
foreach($Lines as $line) {
    $line = explode(" -- ", $line);
    $Output[] = $line[0];
}

var_dump($Output);

示例输出

array (size=3)
  0 => string 'string one' (length=10)
  1 => string 'string three' (length=12)
  2 => string 'string five' (length=11)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 2020-12-13
    • 2010-10-31
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    相关资源
    最近更新 更多