>字符串
"<p>This is </p><p>Stackoverflow</p><p>site for programmers</p>"
所需输出
"This is <p>Stackoverflow</p><p>site for programmers</p>"
小功能
function remove_p($string)
{
$first_p=substr($string,0,3);
$p="<p>";
if($first_p==$p)
{
$string=str_replace('<p>','',$string,$temp=1);
$string=str_replace('</p>','',$string,$temp=1);
}
return $string;
}
但它删除了所有<p> </p>
标签。为什么会这样?我写这篇文章基本上是为了删除 ckeditor 创建的第一段标签。
str_replace
作用于子字符串的所有匹配项,而不仅仅是第一个。您将需要使用其他函数。
$string = preg_replace('~<p>(.*?)</p>~is', '$1', $string, /* limit */ 1);
若要仅删除第一个<p>
并在字符串开头</p>
,请在第一个/
后添加一个^
。
另请参阅:使用 str_replace 以便它只作用于第一场比赛?
function replaceFirst($input, $search, $replacement){
$pos = stripos($input, $search);
if($pos === false){
return $input;
}
else{
$result = substr_replace($input, $replacement, $pos, strlen($search));
return $result;
}
}
$string = "This is <p>Stackoverflow</p><p>site for programmers</p>";
echo $string;
echo replaceFirst($string, '<p>', '');
输出:
This is <p>Stackoverflow</p><p>site for programmers</p>
This is Stackoverflow</p><p>site for programmers</p>
来源: #2031045
希望这有帮助!
$str = "This is <p>Stackoverflow</p><p>site for programmers</p>";
function remove_p($string)
{
$string=str_replace('<p>','',$string,$temp=1);
$string=str_replace('<'p>','',$string,$temp=1);
return $string;
}
echo(remove_p($str));
结果是:
这是堆栈溢出
面向程序员的网站
尝试使用此答案的方法。
function remove_p($string)
{
return replaceFirst(replaceFirst($string, '<p>', ''), '</p>', '');
}
或阅读正则表达式。