我有一個字串,我需要在字串的某個索引處添加一些 html 標簽。
$comment_text = 'neethu and Dilnaz Patel check this'
Array ( [start_index_key] => 0 [string_length] => 6 )
Array ( [start_index_key] => 11 [string_length] => 12 )
我需要在開始索引鍵處使用 string_length 中提到的 long 進行拆分
預期的最終輸出是
$formattedText = '<span>@neethu</span> and <span>@Dilnaz Patel</span> check this'
我該怎么辦?
uj5u.com熱心網友回復:
這是一種非常嚴格的方法,會在第一次更改時中斷。您是否可以控制字串的創建?如果是這樣,您可以創建一個帶有占位符的字串并填充值。
即使您可以使用正則運算式執行此操作:
$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);
但這仍然是一個非常僵化的解決方案。
如果您可以嘗試創建一個帶有名稱占位符的字串。這將在未來更容易管理和改變。
uj5u.com熱心網友回復:
<?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);
說明:
創建陣列引數:偶數索引 (0,2,4,6,8,...) 將是start_index_key奇數索引 (1,3,5,7,9,...)string_length
讀取每個斷點,并將其存盤在$break_open 和$break_close
為結果創建陣列 $result。
回圈您的字串,添加、添加或不添加帶 break_point 的 spann
結果:
string '<span>neethu </span>and <span>Dilnaz Patel </span> check this' (length=61)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326053.html
