0

我想为每个以“。”结尾的句子添加跨度标签。比如:我的字符串:

“我不能说,‘你用一个吻背叛了人子吗?’ 除非我相信背叛。钉十字架的整个信息就是我不相信。

输出/输出:

"<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怎么可能?

4

4 回答 4

1

你可以做

<?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>';
?>
于 2013-06-10T06:38:01.607 回答
1

如果你用“。”来爆炸句子。我想修改上面的代码。

$newText = "";
$count = 0;
foreach (explode(". ",$theText) as $part) {

   if(ctype_upper($part{0}))
   {
      $count++;
      $newText .= "<span id=\"s$count\">$part</span>";
  }

 }

我希望它应该适用于缩写或其他东西。

于 2013-06-10T06:56:09.723 回答
0

试试这个代码,你会得到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;
?>
于 2013-06-10T06:54:06.617 回答
-2

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

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

但是句子中间的句点呢,比如缩写词之类的呢?您可能可以将 a 替换为explodeapreg_split以获得更好的结果。例如,仅当句点之后的字符不是字母或其他句点时才拆分。

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

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

preg_split("/\.\s/",$theText);
于 2013-06-10T06:36:36.163 回答