如何使用php来分解字符串,删除多余的字符


How to use php to explode string, remove extra characters

我使用PHP已经有一段时间了,遇到了一个问题,将字符串转换为数组(爆炸),然后简单地删除每个元素周围的系统输出字符并不容易实现。

我有一系列需要处理输出的类别:

2;#Ecosystems;#3;#Core Science Systems (CSS);#4;#Energy and Minerals;#5;#Director

我试过下面这个特定的代码:

$text = "2;#Ecosystems;#3;#Core Science Systems (CSS);#4;#Energy and Minerals;#5;#Director";
$explode = explode('#' ,  $text);
foreach ($explode as $key => $value)
{
    ob_start();
    echo ''.$value.''; 
    $myStr = ob_get_contents();
    ob_end_clean();
}
echo "$myStr"

返回的唯一元素是:

 Director

有人能给我指正确的方向吗。我想这样查看字符串:

Ecosystems; Core Science Systems (CSS); Energy and Minerals; Director

$myStr = ob_get_contents();

这将取代$myStr。你可能想做的是添加:

$myStr .= ob_get_contents();

尽管查看了所需的输出,但您的代码不会达到您想要的效果,因为您没有删除前面的部分,例如#1;

试试这个

$text = "2;#Ecosystems;#3;#Core Science Systems (CSS);#4;#Energy and Minerals;#5;#Director";
$text = preg_replace('/(#?[0-9];#)/', ' ', $text);
echo $text;

输出:Ecosystems; Core Science Systems (CSS); Energy and Minerals; Director

您的问题与问题无关,每次foreach迭代都会覆盖缓冲区,修复方法是

$myStr .=ob_get_contents();

对于您给出的这个确切的示例,您可以将爆炸更改为split on;#

$text = "2;#Ecosystems;#3;#Core Science Systems (CSS);#4;#Energy and Minerals;#5;#Director";
$categories = array();
$explode = explode(';#' ,  $text);
foreach ($explode as $key => $value)
{
    if (!is_numeric($value)) {
        $categories[] = $value;
    }
}
echo implode("; ", $categories);

原因是您将ob_start()和ob_end_clean()都放置在循环中。将它们放在循环之外:

ob_start();
foreach ($explode as $key => $value)
{
   echo ''.$value.''; 
   $myStr = ob_get_contents();
}
ob_end_clean();
echo "$myStr";

我会使用preg_split并这样做:

$result = implode(' ', preg_split('/#?'d+;#/', $text, null, PREG_SPLIT_NO_EMPTY));

这解决了问题,您可以微调输出:

$text = "2;#Ecosystems;#3;#Core Science Systems (CSS);#4;#Energy and Minerals;#5;#Director";
$explode = explode('#' ,  $text);
$myStr = '';
foreach ($explode as $key => $value)
{
  $myStr .= $value;
}
echo "$myStr"

$arr=爆炸("#",$text);

然后,您可以以不同的方式对阵列进行回波

echo$arr[0]<=数字表示数组值的索引。