首页 > 解决方案 > 查找某个字符并在循环中删除它

问题描述

我正在尝试从全文中找到某个字符并删除该字符并将其存储在变量中

例子;

$text = ',this,is,an,example,'; //dynamic texts always changable

我正在尝试从文本中删除所有逗号(,)并将其存储在变量中,因此它看起来像

$text1 = 'this';
$text2 = 'is';
$text2 = 'an';
$text2 = 'example';

到目前为止,我所学到的和所做的如下

$text = ',this,is,an,example,';
$position = 0;
while (($position = strpos($text, ",", $position)) !== false){
  echo "Found $position<br>";
  $position++;
}

所以我应该在这里看什么样的方法还有其他方法可以做到这一点谢谢。

标签: php

解决方案


一个array会帮助 -

$text = ',this,is,an,example,';

$texts = array_filter(array_map('trim', explode(',', $text)));
// explode - split string by ,
// trim - to remove blank spaces from start & end
// array_filter - remove empty values

输出

array(4) {
  [1]=>
  string(4) "this"
  [2]=>
  string(2) "is"
  [3]=>
  string(2) "an"
  [4]=>
  string(7) "example"
}

如果需要变量,那么 -

$texts = array_values($texts); // to reset the keys and start from 0
foreach ($texts as $i => $t) {
    ${'text' . ($i + 1)} = $t;
}

推荐阅读