我需要在和平中爆炸一个字符串并删除一些字符。最后我想将这个字符串水平放在一起。
这是我尝试的:
$string = "34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.";
$arr = explode("*****", $string);
foreach ($arr as $val) {
$val = trim(substr($val, 0, 2));
$arr_neu[] = $val;
}
$array_neu = implode(" ", $arr);
fwrite($flog, "\nstring neu:" . $array_neu);
这就是我得到的:
34 asdfadfadf。***** 23 vgadfsdfasdf。***** 46 asdfasdfadf。 34 23 46
我只需要数字34 23 46!
谢谢!
答案 0 :(得分:3)
只需使用preg_replace
功能:
$s = '34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.';
$result = trim(preg_replace('/[^0-9 ]+/', '', $s));
print_r($result);
输出:
34 23 46
<强> ---------- 强>
如果字符串可以包含多个连续的空格 - 将上述方法更改为以下内容:
$result = trim(preg_replace('/[^0-9]+/', ' ', $s));
答案 1 :(得分:0)
在代码结束时,您使用错误的变量来破坏数据
将您的代码更改为
$string = "34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.";
$arr = explode("*****", $string);
foreach ($arr as $val) {
$val = trim(substr($val, 0, 2));
$arr_neu[] = $val;
}
$array_neu = implode(" ", $arr_neu); // <--------change here. Use $arr_neu
fwrite($flog, "\nstring neu:" . $array_neu);
答案 2 :(得分:0)
您只需将implode
值更改为$arr_neu
而不是$arr
<?php
$string = "34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.";
$arr = explode("*****", $string);
foreach ($arr as $val) {
$val = trim(substr($val, 0, 2));
$arr_neu[] = $val;
}
$array_neu = implode(" ", $arr_neu);
fwrite($flog, "\nstring neu:" . $array_neu);