替换第n次出现php之后的所有出现


replace all occurrences after nth occurrence php?

我有这个字符串。。。

$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); 

但效果不太好。如果你有想法,请帮忙!

您可以使用:

$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 

RegEx演示

方法是使用^([^|]*'|){8}(*SKIP)(*F)匹配并忽略前8次出现的|,并用空格替换每个|

您可以使用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;

您也可以使用下面的regex,并用一个空格替换匹配的|

$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('~(?:^(?:[^|]*'|){8}|(?<!^)'G)[^|'n]*'K'|~', ' ', $text);

演示

<?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;
?>

这样做的方法是:

$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;

没有正则表达式的示例:

$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的每个条目,返回值也是一个数组。

爆炸:

如果限制设置为正,则返回的数组将包含极限元素的最大值,最后一个元素包含一串