I have a bunch of text ike
Lets say
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy.
And I want to make it so if a word is longer then 5 characters it replaces the characters with +. So that string would become
Lorem Ipsum is simpl+ dummy text of the print+++ and types++++++ indus+++. Lorem Ipsum has been the indus+++++ stand+++ dummy.
But I don't want to include punctuation such as ! and , and . but I do want to include apostrophes '
Any idea how I could do this?
Try this:
$text = "Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy.";
echo preg_replace("/(?<=[\w']{5})[\w']/", '+', $text);
which will output:
Lorem Ipsum is simpl+ dummy text of the print+++ and types++++++ indus+++. Lorem Ipsum has been the indus+++++ stand+++ dummy.
function callback($matches) {
return $matches[1] . str_repeat('+', strlen($matches[2]));
}
$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy.";
$str = preg_replace_callback("#([a-z']{5})([a-z']+)#i", 'callback', $str);
echo $str;
You can use preg_replace for this
$str = "Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's
standard dummy.";
$pattern = "/([a-zA-Z]{5})([a-zA-Z]+)/";
$newStr = preg_replace($pattern,"$1+",$str);
echo $newStr;
// the + added
you have to test this as i dont have php on this machine
We can also use strtr()
preg_match_all('/[\w\']{5}[\w\']+/', $s, $matches);
$dict = array();
foreach($matches[0] as $m){
$dict[$m] = substr($m, 0, 5).str_repeat('+', strlen($m) - 5);
}
$s = strtr($s, $dict);