Php,如何从字符串中添加span标签,以"."结束


Php, how to add span tag to every sentence from string which is end with "."?

我想为每个以"结尾的句子添加span标签。如:我的字符串:

"我怎能说:‘你用亲嘴出卖人子吗?除非我相信背叛。被钉在十字架上的整个信息很简单,就是我没有。"

O/p:

"<span id="s1">I could not have said, ’Betrayest thou the Son of man with a kiss?’ unless I believed in betrayal.</span> <span id="s2">The whole message of the crucifixion was simply that I did not.</span>"

怎么可能用php?

你可以做

<?php
$string="I could not have said, ’Betrayest thou the Son of man with a kiss?’ unless I believed in betrayal. The whole message of the crucifixion was simply that I did not.";
$output=str_replace(". ",'. </span> <span id="s2">',$string);
echo '<span id="s1">'.$output.'</span>';
?>

基于注释编辑

这个版本将确保每个新的替换得到一个新的span id

<?php
$string="I could not have said, ’Betrayest thou the Son of man with a kiss?’ unless I believed in betrayal. The whole message of the crucifixion was simply that I did not. Testing 123. testing again.";
$dots=substr_count($string,". ");
for($i=2;$i<=$dots+2;$i++)
{
$string=preg_replace("/'. /", ".</span> <span id ='"s$i'">" ,$string,1);
}
echo '<span id="s1">'.$string.'</span>';
?>

如果你用"。"。我想修改上面的代码。

$newText = "";
$count = 0;
foreach (explode(". ",$theText) as $part) {
   if(ctype_upper($part{0}))
   {
      $count++;
      $newText .= "<span id='"s$count'">$part</span>";
  }
 }

我希望它应该工作的缩写或其他

试试下面的代码,您将获得span标记的唯一id。

<?php
$str = "I could not have said, 'Betrayest thou the Son of man with a kiss?' unless I believed in betrayal. The whole message of the crucifixion was simply that I did not.";
$exp_str = explode(". ",$str);
$sentence = "<span id='"s1'">";
$n = 2;
foreach($exp_str as $val) {
    $sentence .= $val.".</span> <span id='"s$n'">";
    $n++;
}
$n = $n-1;
$sentence = substr($sentence,0,strpos($sentence,".</span> <span id='"s$n'">"));
echo $sentence;
?>

我不确定preg_replace是否可以做到这一点(因为唯一的id)。否则,可以像这样手动完成:

$newText = "";
$count = 0;
foreach (explode(".",$theText) as $part) {
  $count++;
  $newText .= "<span id='"s$count'">$part</span>";
}

但是句子中间的句号呢,比如缩写之类的?你可以用preg_split代替explode来得到更好的结果。例如,只有当句点后面的字符不是字母或其他句点时才进行分割。

preg_split("/'.[^','w]/",$theText);

或者确保下一个字符是空格。

preg_split("/'.'s/",$theText);