Related
My code so far:
$text = 'Herman Archer LIVEs in neW YORK';
$oldWords = explode(' ', $text);
$newWords = array();
$counter = 0;
foreach ($oldWords as $word) {
for($k=0;$k<strlen($word);$k++)
$counter = 0;
if ($word[k] == strtoupper($word[$k]))
$counter=$counter+1;
if($counter>1)
$word = strtolower($word);
if($counter == 1)
$word = ucfirst(strtolower($word));
else $word = strtolower($word);
echo $word."<br>";
}
Result:
Herman
Archer
Lives
In
New
York
Expected output:
Herman Archer lives in new york
If you want to use the counter approach you could use something as the following
<?php
$text = 'Herman Archer LIVEs in A neW YORK';
$words = explode(' ', $text);
foreach($words as &$word) {
$counter = 0;
for($i = 1; $i <= strlen($word);$i++) {
if (strtoupper($word[$i]) == $word[$i]) $counter++;
if ($counter == 2) break;
}
if ($counter == 2) $word = strtolower($word);
}
echo implode(' ', $words);
Let's do it in a simple manner. Let's loop $oldWords, compare the strings from the second character to the end with their lower-case version and replace if the result is different.
for ($index = 0; $index < count($oldWords); $index++) {
//Skip one-lettered words, such as a or A
if (strlen($oldWords[$index]) > 1) {
$lower = strtolower($oldWords[$index]);
if (substr($oldWords[$index], 1) !== substr($lower, 1)) {
$oldWords[$index] = $lower;
}
}
}
If you are using not only English language, you might want to switch to mb_strtolower
<?php
$text = 'Herman Archer LIVEs in neW YORK';
function normalizeText($text)
{
$words = explode(" ", $text);
$normalizedWords = array_map(function ($word) {
$loweredWord = strtolower($word);
if (ucfirst($loweredWord) === $word) {
return $word;
}
return $loweredWord;
}, $words);
return join(" ", $normalizedWords);
}
echo normalizeText($text) . PHP_EOL; // Herman Archer lives in new york
you can combine ctype_upper for first character and ctype_lower for the rest
$text = 'Herman Archer LIVEs in neW YORK';
$oldWords = explode(' ', $text);
$newWords = '';
foreach ($oldWords as $word) {
if(ctype_upper($word[0])&&ctype_lower(substr($word,1))){
$newWords .= $word.' ';
}else{
$newWords .= strtolower($word).' ';
}
}
echo $newWords;
Meanwhile I've found out that this can be done in an easier way
if(isset($_POST["sumbit"])){
$string = $_POST["string"];
if(!empty($string)){
$word = explode (" ",$string);
foreach($words as $word){
//cut the first letter.
//check caselower.
//if not, attach the letter back and turn all lowercase.
//if yes, attach the letter back and leave it .
$wordCut = substr($word,1);
if(ctype_lower($wordCut)){
echo $word." ";
} else {
echo strtolower($word). " ";
}
}
I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.
I need to replace it in PHP string and MySQL query too.
Example:
Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.
I want to replace word 'place' with 'garden'.
Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.
It should also work with phrases.
I've created a function that will replace the word for you and keep the cases.
function replaceWithCase($source, $replacement, $string) {
// Does the string contain the source word?
if (strpos($string, $source) === false) {
return false;
}
// If everything is uppercase, return the replacement fully uppercase
if (ctype_upper($source)) {
return str_replace($source, strtoupper($replacement));
}
// Set an array to work with
$characters = array();
// Split the source into characters
$sourceParts = explode('', $source);
// Loop throug the characters and set the case
foreach ($sourceParts as $k => $sp) {
if (ctype_upper($sp)) {
$characters[$k] = true;
} else {
$characters[$k] = false;
}
}
// Split the replacement into characters
$replacementParts = explode('', $replacement);
// Loop through characters and compare their case type
foreach ($replacementParts as $k => $rp) {
if (array_key_exists($k, $characters) && $characters[$k] === true) {
$newWord[] = strtoupper($rp);
} else {
$newWord[] = strtolower($rp);
}
}
return substr_replace($source, implode('', $newWord), $string);
}
// usage
echo replaceWithCase('AppLes', 'bananas', 'Comparing AppLes to pears');
Note: it is untested and might need some tweaking
function stringReplace($findStr, $replaceStr, $str)
{
$isLowerStr = true;
for($i=0; $i<strlen($findStr); $i++){
if(ord($findStr[$i]) >= 97 && ord($findStr[$i])<=122){
if(ord($replaceStr[$i]) >= 65 && ord($replaceStr[$i])<=96){
$replaceStr[$i] = strtolower($replaceStr[$i]);
}else{
$replaceStr[$i] = $replaceStr[$i];
}
}else{
$isLowerStr = false;
$replaceStr[$i] = strtoupper($replaceStr[$i]);
}
}
if($isLowerStr == false){
if(strlen($replaceStr) > strlen($findStr)){
for($i=0;$i<(strlen($replaceStr)-strlen($findStr));$i++){
if(strtoupper($findStr) == $findStr){
$replaceStr[strlen($findStr)+$i] = strtoupper($replaceStr[strlen($findStr)+$i]);
}else{
$replaceStr[strlen($findStr)+$i] = strtolower($replaceStr[strlen($findStr)+$i]);
}
}
}
}
echo str_replace($findStr, $replaceStr, $str);die;
}
$findStr = 'Place';
$replaceStr = 'garden';
echo stringReplace($findStr, $replaceStr, 'Potato is jumping all over the '.$findStr.'.');
So I managed to create my own function in the end. Thanks for help and inspiration though.
function replaceWithCase($source, $replacement, $string, $pos = 0) {
while (($pos = strpos(strtolower($string), strtolower($source), $pos))!== false) {
$substr = mb_substr($string, $pos, strlen($source));
$remaining = mb_substr($string, $pos + strlen($source));
if (ctype_upper($substr)) {
$string = substr_replace($string,strtoupper($replacement),$pos,strlen($source));
continue;
}
$substrParts = preg_split('//u', $substr, null, PREG_SPLIT_NO_EMPTY);
$replaceParts = preg_split('//u', $replacement, null, PREG_SPLIT_NO_EMPTY);
$newWord = '';
foreach ($replaceParts as $k => $rp) {
if (array_key_exists($k,$substrParts))
$newWord .= ctype_upper($substrParts[$k]) ? mb_strtoupper($rp) : mb_strtolower($rp);
else
$newWord .= $rp;
}
$string = substr_replace($string,$newWord,$pos,strlen($source));
$pos = $pos + strlen($source);
}
return $string;
}
echo replaceWithCase("place", "garden", "Potato is jumping all over the PLACE");
echo "<br>";
echo replaceWithCase("jumping", "running", "Potato is jumping all over the pLAcE");
echo "<br>";
echo replaceWithCase("jumping", "cry", "Potato is jumping all over the place");
echo "<br>";
echo replaceWithCase("all", "", "Potato is jumping all over the Place");
echo "<br>";
echo replaceWithCase(" ", ";", "Potato is jumping all over the Place", 10);
echo "<br>";
Output:
Potato is jumping all over the GARDEN
Potato is running all over the pLAcE
Potato is cry all over the place
Potato is jumping over the Place
Potato is jumping;all;over;the;Place
Thanks #LadaB - that's a really helpful function but it also replaces partial word matches. Sometimes you might want this, but in others cases you won't, for example if you have:
$source = 'mom';
$replacement = 'mum'; // british spelling of "mom"
$string = 'Be in the moment with your Mom.';
You get: "Be in the mument with your Mum."
So, I have added an option to make the match "whole word only".
I found another issue where multibyte characters would shift where the capitalization ended up, which seems to be fixed by changing. mb_substr to substr.
I also removed the unused:
$remaining = substr($string, $pos + strlen($source));
My latest (I think fully working) version is:
function replaceWithCase($source, $replacement, $string, $wholeWordOnly = false) {
$pos = 0;
while (($pos = strpos(strtolower($string), strtolower($source), $pos))!== false) {
if($wholeWordOnly) {
preg_match("/\b".$string[$pos]."/", $string[($pos-1)] . $string[$pos], $start);
preg_match("/".$string[($pos+strlen($source)-1)]."\b/", $source . $string[($pos+strlen($source))], $end);
}
if(($wholeWordOnly && $start && $end) || !$wholeWordOnly) {
$substr = substr($string, $pos, strlen($source));
if (ctype_upper($substr)) {
$string = substr_replace($string,strtoupper($replacement),$pos,strlen($source));
continue;
}
$substrParts = preg_split('//u', $substr, -1, PREG_SPLIT_NO_EMPTY);
$replaceParts = preg_split('//u', $replacement, -1, PREG_SPLIT_NO_EMPTY);
$newWord = '';
foreach ($replaceParts as $k => $rp) {
if (array_key_exists($k,$substrParts))
$newWord .= ctype_upper($substrParts[$k]) ? mb_strtoupper($rp) : mb_strtolower($rp);
else
$newWord .= $rp;
}
$string = substr_replace($string,$newWord,$pos,strlen($source));
}
$pos = $pos + strlen($source);
}
return $string;
}
Hope that helps you or someone else.
Use "stripos" php function
$str = 'Potato is jumping all over the pLAcEs.';
$str_new = "garden";
$str1 = str_split($str_new);
$pos = stripos($str,'places');
$string = substr($str,$pos,6);
$extrct = str_split($string);
$var = '';
foreach ($extrct as $key => $value) {
if(ctype_upper($value))
{
$var .= strtoupper($str1[$key]);
}else{
$var .= strtolower($str1[$key]);
}
}
$new_string = str_replace($string, $var, $str);
echo $new_string; //Potato is jumping all over the gARdEn.
I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.
I need to replace it in PHP string and MySQL query too.
Example:
Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.
I want to replace word 'place' with 'garden'.
Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.
It should also work with phrases.
I've created a function that will replace the word for you and keep the cases.
function replaceWithCase($source, $replacement, $string) {
// Does the string contain the source word?
if (strpos($string, $source) === false) {
return false;
}
// If everything is uppercase, return the replacement fully uppercase
if (ctype_upper($source)) {
return str_replace($source, strtoupper($replacement));
}
// Set an array to work with
$characters = array();
// Split the source into characters
$sourceParts = explode('', $source);
// Loop throug the characters and set the case
foreach ($sourceParts as $k => $sp) {
if (ctype_upper($sp)) {
$characters[$k] = true;
} else {
$characters[$k] = false;
}
}
// Split the replacement into characters
$replacementParts = explode('', $replacement);
// Loop through characters and compare their case type
foreach ($replacementParts as $k => $rp) {
if (array_key_exists($k, $characters) && $characters[$k] === true) {
$newWord[] = strtoupper($rp);
} else {
$newWord[] = strtolower($rp);
}
}
return substr_replace($source, implode('', $newWord), $string);
}
// usage
echo replaceWithCase('AppLes', 'bananas', 'Comparing AppLes to pears');
Note: it is untested and might need some tweaking
function stringReplace($findStr, $replaceStr, $str)
{
$isLowerStr = true;
for($i=0; $i<strlen($findStr); $i++){
if(ord($findStr[$i]) >= 97 && ord($findStr[$i])<=122){
if(ord($replaceStr[$i]) >= 65 && ord($replaceStr[$i])<=96){
$replaceStr[$i] = strtolower($replaceStr[$i]);
}else{
$replaceStr[$i] = $replaceStr[$i];
}
}else{
$isLowerStr = false;
$replaceStr[$i] = strtoupper($replaceStr[$i]);
}
}
if($isLowerStr == false){
if(strlen($replaceStr) > strlen($findStr)){
for($i=0;$i<(strlen($replaceStr)-strlen($findStr));$i++){
if(strtoupper($findStr) == $findStr){
$replaceStr[strlen($findStr)+$i] = strtoupper($replaceStr[strlen($findStr)+$i]);
}else{
$replaceStr[strlen($findStr)+$i] = strtolower($replaceStr[strlen($findStr)+$i]);
}
}
}
}
echo str_replace($findStr, $replaceStr, $str);die;
}
$findStr = 'Place';
$replaceStr = 'garden';
echo stringReplace($findStr, $replaceStr, 'Potato is jumping all over the '.$findStr.'.');
So I managed to create my own function in the end. Thanks for help and inspiration though.
function replaceWithCase($source, $replacement, $string, $pos = 0) {
while (($pos = strpos(strtolower($string), strtolower($source), $pos))!== false) {
$substr = mb_substr($string, $pos, strlen($source));
$remaining = mb_substr($string, $pos + strlen($source));
if (ctype_upper($substr)) {
$string = substr_replace($string,strtoupper($replacement),$pos,strlen($source));
continue;
}
$substrParts = preg_split('//u', $substr, null, PREG_SPLIT_NO_EMPTY);
$replaceParts = preg_split('//u', $replacement, null, PREG_SPLIT_NO_EMPTY);
$newWord = '';
foreach ($replaceParts as $k => $rp) {
if (array_key_exists($k,$substrParts))
$newWord .= ctype_upper($substrParts[$k]) ? mb_strtoupper($rp) : mb_strtolower($rp);
else
$newWord .= $rp;
}
$string = substr_replace($string,$newWord,$pos,strlen($source));
$pos = $pos + strlen($source);
}
return $string;
}
echo replaceWithCase("place", "garden", "Potato is jumping all over the PLACE");
echo "<br>";
echo replaceWithCase("jumping", "running", "Potato is jumping all over the pLAcE");
echo "<br>";
echo replaceWithCase("jumping", "cry", "Potato is jumping all over the place");
echo "<br>";
echo replaceWithCase("all", "", "Potato is jumping all over the Place");
echo "<br>";
echo replaceWithCase(" ", ";", "Potato is jumping all over the Place", 10);
echo "<br>";
Output:
Potato is jumping all over the GARDEN
Potato is running all over the pLAcE
Potato is cry all over the place
Potato is jumping over the Place
Potato is jumping;all;over;the;Place
Thanks #LadaB - that's a really helpful function but it also replaces partial word matches. Sometimes you might want this, but in others cases you won't, for example if you have:
$source = 'mom';
$replacement = 'mum'; // british spelling of "mom"
$string = 'Be in the moment with your Mom.';
You get: "Be in the mument with your Mum."
So, I have added an option to make the match "whole word only".
I found another issue where multibyte characters would shift where the capitalization ended up, which seems to be fixed by changing. mb_substr to substr.
I also removed the unused:
$remaining = substr($string, $pos + strlen($source));
My latest (I think fully working) version is:
function replaceWithCase($source, $replacement, $string, $wholeWordOnly = false) {
$pos = 0;
while (($pos = strpos(strtolower($string), strtolower($source), $pos))!== false) {
if($wholeWordOnly) {
preg_match("/\b".$string[$pos]."/", $string[($pos-1)] . $string[$pos], $start);
preg_match("/".$string[($pos+strlen($source)-1)]."\b/", $source . $string[($pos+strlen($source))], $end);
}
if(($wholeWordOnly && $start && $end) || !$wholeWordOnly) {
$substr = substr($string, $pos, strlen($source));
if (ctype_upper($substr)) {
$string = substr_replace($string,strtoupper($replacement),$pos,strlen($source));
continue;
}
$substrParts = preg_split('//u', $substr, -1, PREG_SPLIT_NO_EMPTY);
$replaceParts = preg_split('//u', $replacement, -1, PREG_SPLIT_NO_EMPTY);
$newWord = '';
foreach ($replaceParts as $k => $rp) {
if (array_key_exists($k,$substrParts))
$newWord .= ctype_upper($substrParts[$k]) ? mb_strtoupper($rp) : mb_strtolower($rp);
else
$newWord .= $rp;
}
$string = substr_replace($string,$newWord,$pos,strlen($source));
}
$pos = $pos + strlen($source);
}
return $string;
}
Hope that helps you or someone else.
Use "stripos" php function
$str = 'Potato is jumping all over the pLAcEs.';
$str_new = "garden";
$str1 = str_split($str_new);
$pos = stripos($str,'places');
$string = substr($str,$pos,6);
$extrct = str_split($string);
$var = '';
foreach ($extrct as $key => $value) {
if(ctype_upper($value))
{
$var .= strtoupper($str1[$key]);
}else{
$var .= strtolower($str1[$key]);
}
}
$new_string = str_replace($string, $var, $str);
echo $new_string; //Potato is jumping all over the gARdEn.
I have a working function that strips profanity words.
The word list is compose of 1700 bad words.
My problem is that it censored
'badwords '
but not
'badwords.' , 'badwords' and the like.
If I chose to remove space after
$badword[$key] = $word;
instead of
$badword[$key] = $word." ";
then I would have a bigger problem because if the bad word is CON then it will stripped a word CONSTANT
My question is, how can i strip a WORD followed by special characters except space?
badword. badword# badword,
.
function badWordFilter($data)
{
$wordlist = file_get_contents("badwordsnew.txt");
$words = explode(",", $wordlist);
$badword = array();
$replacementword = array();
foreach ($words as $key => $word)
{
$badword[$key] = $word." ";
$replacementword[$key] = addStars($word);
}
return str_ireplace($badword,$replacementword,$data);
}
function addStars($word)
{
$length = strlen($word);
return "*" . substr($word, 1, 1) . str_repeat("*", $length - 2)." " ;
}
Assuming that $data is a text that needs to be censored, badWordFilter() will return the text with bad words as *.
function badWordFilter($data)
{
$wordlist = file_get_contents("badwordsnew.txt");
$words = explode(",", $wordlist);
$specialCharacters = ["!","#","#","$","%","^","&","*","(",")","_","+",".",",",""];
$dataList = explode(" ", $data);
$output = "";
foreach ($dataList as $check)
{
$temp = $check;
$doesContain = contains($check, $words);
if($doesContain != false){
foreach($specialCharacters as $character){
if($check == $doesContain . $character || $check == $character . $doesContain ){
$temp = addStars($doesContain);
}
}
}
$output .= $temp . " ";
}
return $output;
}
function contains($str, array $arr)
{
foreach($arr as $a) {
if (stripos($str,$a) !== false) return $a;
}
return false;
}
function addStars($word)
{
$length = strlen($word);
return "*" . substr($word, 1, 1) . str_repeat("*", $length - 2)." " ;
}
Sandbox
I was able to answer my own question with the help of #maxchehab answer, but I can't declared his answer because it has fault at some area. I am posting this answer so others can use this code when they need a BAD WORD FILTER.
function badWordFinder($data)
{
$data = " " . $data . " "; //adding white space at the beginning and end of $data will help stripped bad words located at the begging and/or end.
$badwordlist = "bad,words,here,comma separated,no space before and after the word(s),multiple word is allowed"; //file_get_contents("badwordsnew.txt"); //
$badwords = explode(",", $badwordlist);
$capturedBadwords = array();
foreach ($badwords as $bad)
{
if(stripos($data, $bad))
{
array_push($capturedBadwords, $bad);
}
}
return badWordFilter($data, $capturedBadwords);
}
function badWordFilter($data, array $capturedBadwords)
{
$specialCharacters = ["!","#","#","$","%","^","&","*","(",")","_","+",".",","," "];
foreach ($specialCharacters as $endingAt)
{
foreach ($capturedBadwords as $bad)
{
$data = str_ireplace($bad.$endingAt, addStars($bad), $data);
}
}
return trim($data);
}
function addStars($bad)
{
$length = strlen($bad);
return "*" . substr($bad, 1, 1) . str_repeat("*", $length - 2)." ";
}
$str = 'i am bad words but i cant post it here because it is not allowed by the website some bad words# here with bad. ending in specia character but my code is badly strong so i can captured and striped those bad words.';
echo "$str<br><br>";
echo badWordFinder($str);
I am trying to remove all leading and trailing <br> in a string using PHP.
Here is an example
<br><br>
Hello<br>
World<br>
<p>This is a message<br>...</p>
<br><br><br><br>
I want to return
Hello<br>
World<br>
<p>This is a message<br>...</p>
I tried to do the following
echo trim($str, '<br>');
But it does not remove them. How can I remove the new line html code?
Use preg_replace with the beginning ^ and end $ anchors:
$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/', '', $string);
Or for multiple lines:
$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/m', '', $string);
You could also trim() it multiple times:
while($string !== ($string = trim($string, '<br>'))){}
This function does the job. Also applicable to anything else really.
//remove all leading and trailing occurences of needle ($n) from haystack ($h)
function trimAll($h, $n){
if(!$h = trim($h,$n)){
trimAll($h, $n);
}
return $h;
}
I wrote this function that will do the job a little better as it gives me more flexibility on what characters to remove and when this function by default will first remove the leading/trailing characters in order:
any tabs
any new lines
any
any
any tabs
any new lines
function trimString($str, $myList = array("\t","\n", "<br>","<br />", "\t","\n") ){
if( ! is_array($myList) ){
$charsToTrim[] = $chr;
} else {
$charsToTrim = $myList;
}
foreach($charsToTrim as $chr){
$len = strlen($chr);
$nlen = $len * -1;
while( substr($str, 0, $len) == $chr){
$str = trim(substr($str, $len));
}
while( substr($str, $nlen) == $chr){
$str = trim(substr($str, 0, $nlen));
}
}
return $str;
}
to use
// default use case
echo trimString($message);
or
//remove only one string
echo trimString($message, '<br>'); // remove only the leading training '<br>'
or
//remove more than 1 string in order
echo trimString($message, array('<br>'<br />') );
I hope this helps someone out there :)
$p=array(
'<br><br>',
'Hello<br>',
'World<br>',
'<p>This is a message<br>...</p>',
'<br><br><br><br>'
);
function trimdeluxe($str, $sub)
{
$parts=explode($sub, $str);
for ($x=0; $x<2; $x++) {
foreach ($parts as $i=>$v) {
if (!strlen($v)) {
unset($parts[$i]);
} else {
break;
}
}
$parts=array_reverse($parts);
}
return implode($sub,$parts);
}
foreach ($p as $str) {
print $str . ' -> ' . trimdeluxe($str, '<br>') . "\n";
}