我有这个字符串......
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|"
如何替换所有出现的|用" "在第8次之后发生|从字符串的开头?
我需要它看起来像1|2|1400|34|A|309|Frank|william|This is the line here
$find = "|";
$replace = " ";
我试过
$text = preg_replace(strrev("/$find/"),strrev($replace),strrev($text),8);
但它没有那么好用。如果您有任何想法请帮忙!
答案 0 :(得分:2)
您可以使用:
$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('/^([^|]*\|){8}(*SKIP)(*F)|\|/', ' ', $text);
//=> 1|2|1400|34|A|309|Frank|william|This is the line here
方法是使用|
匹配并忽略^([^|]*\|){8}(*SKIP)(*F)
的前8次出现,并用空格替换每个|
。
答案 1 :(得分:2)
您可以使用explode()
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$arr = explode('|', $text);
$result = '';
foreach($arr as $k=>$v){
if($k == 0) $result .= $v;
else $result .= ($k > 7) ? ' '.$v : '|'.$v;
}
echo $result;
答案 2 :(得分:1)
您也可以使用以下正则表达式,并将匹配的|
替换为单个空格。
$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('~(?:^(?:[^|]*\|){8}|(?<!^)\G)[^|\n]*\K\|~', ' ', $text);
答案 3 :(得分:0)
<?php
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$texts = explode( "|", $text );
$new_text = '';
$total_words = count( $texts );
for ( $i = 0; $i < $total_words; $i++)
{
$new_text .= $texts[$i];
if ( $i <= 7 )
$new_text .= "|";
else
$new_text .= " ";
}
echo $new_text;
?>
答案 4 :(得分:0)
这样做的方法是:
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$arr = explode('|', $text, 9);
$arr[8] = strtr($arr[8], array('|'=>' '));
$result = implode('|', $arr);
echo $result;
答案 5 :(得分:0)
没有正则表达式的示例:
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$array = str_replace( '|', ' ', explode( '|', $text, 9 ) );
$text = implode( '|', $array );
<强> str_replace函数:强>
如果subject是一个数组,则执行搜索和替换 主题的每个条目,返回值也是一个数组。
<强>爆炸:强>
如果设置了limit并且为正数,则返回的数组将包含a 最大元素,最后一个元素包含其余元素 字符串。