Home > Back-end >  how to split string and add additional strin to it
how to split string and add additional strin to it

Time:10-19

i have a string and i need to add some html tag at certain index of the string.

$comment_text = 'neethu and Dilnaz Patel  check this'
Array ( [start_index_key] => 0 [string_length] => 6 )
Array ( [start_index_key] => 11 [string_length] => 12 )

i need to split at start index key with long mentioned in string_length

expected final output is

$formattedText = '<span>@neethu</span> and <span>@Dilnaz Patel</span>  check this'

what should i do?

CodePudding user response:

This is a very strict method that will break at the first change. Do you have control over the creation of the string? If so, you can create a string with placeholders and fill the values.

Even though you can do this with regex:

$pattern = '/(. [^ ])\s and (. [^ ])\s check this/i';
$string = 'neehu and Dilnaz Patel  check this';
$replace = preg_replace($pattern, '<b>@$\1</b> and <b>@$\2</b>  check this', $string);

But this is still a very rigid solution.

If you can try creating a string with placeholders for the names. this will be much easier to manage and change in the future.

CodePudding user response:

<?php



function my_replace($string,$array_break)
{
    $break_open = array();
    $break_close = array();
    
    $start = 0;
    foreach($array_break as $key => $val)
    {
        // for tag <span>
        if($key % 2 == 0)
        {
            $start = $val;
            $break_open[] = $val;
        }
        else
        {
            // for tag </span>
            $break_close[] = $start   $val;
        }
    }
    
    $result = array();
    for($i=0;$i<strlen($string);$i  )
    {
        $current_char = $string[$i];
        
        if(in_array($i,$break_open))
        {
            $result[] = "<span>".$current_char;
        }
        else if(in_array($i,$break_close))
        {
            $result[] = $current_char."</span>";
        }
        else
        {
            $result[] = $current_char;
        }
        
    }
    return implode("",$result);
}

$comment_text = 'neethu and Dilnaz Patel  check this';


$my_result =  my_replace($comment_text,array(0,6,11,12));

var_dump($my_result);

Explaination:

Create array parameter with: The even index (0,2,4,6,8,...) would be start_index_key and The odd index (1,3,5,7,9,...) would be string_length

read every break point , and store it in $break_open and $break_close

create array $result for result.

Loop your string, add , add or dont add spann with break_point

Result: string '<span>neethu </span>and <span>Dilnaz Patel </span> check this' (length=61)

  • Related