【问题标题】:Get all string after specific value in php在php中获取特定值之后的所有字符串
【发布时间】:2019-04-03 21:23:15
【问题描述】:

我需要所需的输出,无论是 preg_match 还是 explode 都不是问题。我需要给定数组格式的输出。

我正在尝试从这个变量中拆分字符串

输入

嗨,FF_nm, 您的城市是 FF_city,您的性别是 FF_gender。网络研讨会标题为 FF_extraparam1 你的名字又是 FF_nickname

输出

array => [昵称,城市,性别,extraparam1,昵称]

代码

<?php
    $data = "Hi FF_nm,
Your city is  FF_city and your gender is FF_gender. webinar title is FF_extraparam1
Again your name is FF_nickname";

    if (($pos = strpos($data, "FIELDMERGE_")) !== FALSE) { 
        $whatIWant = substr($data, $pos+1); 
    }

    echo $whatIWant; 

    ?>

【问题讨论】:

  • 有什么问题?您正在尝试或想要的 preg_* 用法是什么?
  • 我需要所需的输出,无论是 preg_match 还是 explode 都不是问题。我需要给定数组格式的输出

标签: php arrays preg-replace preg-match


【解决方案1】:

您可以将explodeforeach 循环用作:

$arr = explode("FIELDMERGE_", $data);
array_shift($arr); // you don't need the first element
foreach($arr as $e) {
    $word = array_shift(explode(" ", $e)); //take the first word
    $res[] = preg_replace('/[^a-z\d]/i', '', $word); //remove the , / . / \n and so on...
}

参考:array-shiftexplodepreg-replace

现场示例:https://3v4l.org/Oa1sn

【讨论】:

  • 我得到像Array ( [0] =&gt; nicknameYour [1] =&gt; city [2] =&gt; gender [3] =&gt; extraparamAgain [4] =&gt; nickname )这样的输出
  • 我需要像Array ( [0] =&gt; nickname[1] =&gt; city [2] =&gt; gender [3] =&gt; extraparam1 [4] =&gt; nickname )这样的输出
  • @QuestionUser 已将 \d 添加到正则表达式 - 希望现在一切正常。在3v4l.org/Oa1sn 中还添加了实时示例
【解决方案2】:

您可以将preg_match_all 与积极的后向模式一起使用。

preg_match_all('/(?<=FF_)\w+/', $data, $fields);
$output = $fields[0];

【讨论】:

    猜你喜欢
    • 2019-04-22
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多