This question already has an answer here:
I would like to add span tag for every sentence which ended with "." like: my 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."
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>"
how it possible with php?
</div>
You could do
<?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>';
?>
Edit Based on Comments
This version will make sure every new replacement gets a new 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>';
?>
I'm not sure if preg_replace can do this (because of the unique IDs). Otherwise it can be manually done like this:
$newText = "";
$count = 0;
foreach (explode(".",$theText) as $part) {
$count++;
$newText .= "<span id=\"s$count\">$part</span>";
}
But what about periods mid sentence, as in abbreviations or something? You could probably replace the explode
with a preg_split
to get a better result. For instance only split if the char right after the period is not a letter or another period.
preg_split("/\.[^\,\w]/",$theText);
Or just ensure the next char is a whitespace.
preg_split("/\.\s/",$theText);
Try this code, You will get unique id for span
tag.
<?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;
?>
If you explode the sentence with ". ". I want to modify the code above.
$newText = "";
$count = 0;
foreach (explode(". ",$theText) as $part) {
if(ctype_upper($part{0}))
{
$count++;
$newText .= "<span id=\"s$count\">$part</span>";
}
}
I hope it should work for abbreviations or something.