PHP Explode Show Seperator
So, I wrote the following code to show words after the fourth full stop / period in a sentence.
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$minText = explode(".", $text);
for($i = $limit; $i < count($minText); $i++){
echo $minText[$i];
}
The algorithm works and it shows me the rest of the sentence after the fourth "." full stop / period .... My problem is that the output doesn't show full stops in a sentence, so it only shows me text without correct punctuation "..... Could someone please help me to find out how to fix the code to display full stops / periods as well?
Thank you so much
source to share
If you want to split it into periods between words, but save it at the end as actual punctuation, you can use it preg_replace()
to convert the periods to another character and then blow it up.
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
//replace periods if they are follwed by a alphanumeric character
$toSplit = preg_replace('/\.(?=\w)/', '#', $text);
$minText = explode("#", $toSplit);
for($i = $limit; $i < count($minText); $i++){
echo $minText[$i] . "<br/>";
}
What is the yield
seperated
with
full
stops.
Of course, if you just want to print all complete stops, add them after echo
this term.
echo $minText[$i] . ".";
source to share
Instead of splitting the input string and then repeating it, you can find the nth position of the delimiter (.) In the string using the strpos () function by changing the offset parameter.
Then, it's just a matter of printing a substring from the position we just defined.
<?php
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$pos = 0;
//find the position of 4th occurrence of dot
for($i = 0; $i < $limit; $i++) {
$pos = strpos($text, '.', $pos) + 1;
}
print substr($text, $pos);
source to share