FRANK
FRANK

Reputation: 51

replace all occurrences after nth occurrence php?

I have this string...

$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|"

How do I replace all the occurrences of | with " " after the 8th occurrence of | from the beginning of the string?

I need it look like this, 1|2|1400|34|A|309|Frank|william|This is the line here

$find = "|";
$replace = " ";

I tried

$text = preg_replace(strrev("/$find/"),strrev($replace),strrev($text),8); 

but its not working out so well. If you have an idea please help!

Upvotes: 1

Views: 244

Answers (6)

Danijel
Danijel

Reputation: 12699

Example without regex:

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

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

explode:

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89565

The way to do that is:

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

Upvotes: 0

MH2K9
MH2K9

Reputation: 12039

You can use 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;

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174736

You could use the below regex also and replace the matched | with a single space.

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

DEMO

Upvotes: 1

CS GO
CS GO

Reputation: 912

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

Upvotes: 0

anubhava
anubhava

Reputation: 785316

You can use:

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

Approach is to match and ignore first 8 occurrences of | using ^([^|]*\|){8}(*SKIP)(*F) and the replace each | by space.

Upvotes: 3

Related Questions