php - 查找某个字符并在循环中删除它
问题描述
我正在尝试从全文中找到某个字符并删除该字符并将其存储在变量中
例子;
$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++;
}
所以我应该在这里看什么样的方法还有其他方法可以做到这一点谢谢。
解决方案
一个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;
}
推荐阅读
- r - Finding index of vector from two other vectors
- java - Android Tabview + Webview
- c# - Difference in behavior between generic and non-generic WeakReference
- ios - SwiftUI NavigationItem doesn't respond
- python - pandas dataframe isin greater than value
- android - ActivityResult API dependency conflict
- docker - Create new verison of docker image
- unity3d - Unity really slow when playing
- firebase - Firebase pagination and filtering at the same time in Flutter
- python-3.x - 字典中具有重复值的键