【问题标题】:PHP Explode and Implode a StringPHP 爆炸和内爆字符串
【发布时间】:2015-04-26 21:10:49
【问题描述】:

我已经完成了一半,并且对输出的内爆感到震惊。

我有一个字符串

$text = "test | (3), new | (1), hello | (5)";
$text = explode(",", $text);
foreach ($text as $t){
    $tt = explode(" | ", $t);
    print_r($tt[0]);
}

当我打印上面的数组时,它会根据需要给我test new hello,现在,我需要像这样添加一个逗号test, new, hello

我搜索但无法实现,因此在此发帖寻求帮助。

【问题讨论】:

    标签: php explode implode


    【解决方案1】:
    $text = "test | (3), new | (1), hello | (5)";
    echo preg_replace('# \| \(.*?\)#', '', $text);
    

    编辑: 达到类似的结果 “测试”、“新”、“你好”

    $text = "test | (3), new | (1), hello | (5)";
    $text = preg_replace('# \| \(.*?\)#', '', $text);
    echo "'" . preg_replace('#,#', "', '", $text) . "'";
    

    【讨论】:

    • 太棒了,谢谢,您的最终编辑成功了。您能否在 preg_replace 中解释一下,您做得如何?我会接受这个答案。
    • @sammry,这是使用正则表达式匹配(然后用空字符串替换),也称为正则表达式。以下是快速搜索到的内容,可以帮助您了解想法并了解如何使用它们:regexone.com/cheatsheet
    • 对了,如果非要这样引用的话,'test',' 'new', 'hello'?
    • 匹配“|(X)”模式,只是转义|符号,因为未转义意味着 OR,exaping ( 和 ) 因为它也是符号,.*?这意味着里面的所有东西都将匹配“非贪婪”。 # 这是开始停止标志
    • 你不觉得正则表达式有点矫枉过正吗?一些简单的 php 方法可以做到这一点,例如 implode?
    【解决方案2】:

    是的,您可以稍后将它们推送到数组和implode

    $text = "test | (3), new | (1), hello | (5)";
    
    $text = explode(",", $text);
    
    $arr = array();
    
    foreach ($text as $t){
        $tt = explode(" | ", $t);
        $arr[] = $tt[0];
    }
    
    echo implode(", ", $arr);
    

    【讨论】:

    • 谢谢,如果非要这样引用的话,'test',''new','hello'?
    • $arr[] = "'".$tt[0]."'";
    【解决方案3】:

    1- Implode 是 php 中的一个函数,您可以在其中将数组转换为字符串 前任-

    $arr = array('Hello','World!','Beautiful','Day!');
    
    echo implode(" ",$arr);
    
    ?>
    

    2- Explode 是 php 中的一个函数,可以将字符串转换为数组

    前-

    $str = "Hello world. It's a beautiful day.";
    
    print_r (explode(" ",$str));
    

    ?> `

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      相关资源
      最近更新 更多