I have a problem costomizing a script i found.
The script looks as the following:
function spin($var){
$words = explode("{",$var);
foreach ($words as $word)
{
$words = explode("}",$word);
foreach ($words as $word)
{
$words = explode("|",$word);
$word = $words[array_rand($words, 1)];
echo $word." ";
}
}
}
$text = "Digitalpoint.com is {the best forum|a great Forum|a wonderful Forum|a perfect Forum} {123|some other sting}";
spin($text);
I'd like to customize the script to return the value of the result.
Example:
$spin = spin($text);
echo $spin;
I've tried to generate a result variable by
$output = $output + $word." ";
return $output;
and then
$spin = spin($text);
echo $spin;
But i've always got result "0"... Can anyone come up with a clever solution for this problem? I'm looking forward to any tips/hints, thanks in advance!
Try this. The spun function wasn't returning a value. Instead of using echo, we'll just append the results onto string $spun and return that.
function spin($var){
$spun = "";
$words = explode("{",$var);
foreach ($words as $word)
{
$words = explode("}",$word);
foreach ($words as $word)
{
$words = explode("|",$word);
$word = $words[array_rand($words, 1)];
$spun .= $word." ";
}
}
return $spun;
}
This bit says that $output is the sum of $output and $word:
$output = $output + $word." ";
return $output;
Because they are not numbers, 0 is returned.
Try using these statements:
$output .= $word . " ";
return $output;
The problem is not in the code you provided, it's in the return statement you specified later on.
$output .= $word." ";
return $output;
I changed the function so that you are not duplicating variable names
function spin($var){
$words = explode("{",$var);
foreach ($words as $word)
{
$words2 = explode("}",$word);
foreach ($words2 as $word2)
{
$words3 = explode("|",$word2);
$word3 = $words3[array_rand($words3, 1)];
echo $word3." ";
}
}
}
and i seem to be getting random phrases from the text. is this what you want?
This can also be done with just a preg_replace_callback:
function spin($text)
{
return preg_replace_callback('/\{(.+?)\}/',
function($matches) {
$values = explode('|', $matches[1]);
return $values[array_rand($values)];
},
$text);
}
Related
I have to check a array of string data .
For example this is the string :
$keywords="today, tomorroy, world, is a good day , a good day is, today"
I have to check if is single word or multi word.
If is multi word i have to order and leave only one for example : is a good day ; a good day is i have to leave only : is a good day . This words i have to store in other array.
In the end i have to have only this results:
This is my code:
$keywords = "";
$singleword="";
$multiword="";
foreach ($response->getResults() as $result) {
$keywords .= $result->getText()->getValue() . ",";
if(count(explode(' ', $keywords)) > 1) {
$multiword++;
}
$singleword++;
}
return $keywordsgenerated;
I need to return : today, tomorroy, world, is a good day
Please can you help me to fix , i'm new in php.
EDIT
I think you were looking for something like this:
<?php
$keywords="today, tomorrow, world, is a good day , a good day is, today";
$arr = array_unique(explode(",",$keywords));
$words = [];
foreach($arr as $key=>$a) {
$words_explode = explode(" ", $a);
foreach($words_explode as $w) {
$words[] = $w;
}
}
$new_words = array_unique($words);
$result = implode(" ", $new_words);
foreach($arr as $item) {
$result = str_replace($item,$item.",",$result);
}
$result = trim($result,", ");
var_dump($result);
UPDATE:
I think? I got what you were looking for?
$keywords = "hansgrohe,hansgrohe focus,küchenarmatur,hansgrohe metris";
$arr = explode(',', $keywords);
$already = [];
$result = '';
foreach($arr as $word) {
$subword = explode(" ", $word);
foreach($subword as $actual_word) {
if (!in_array($actual_word, $already)) {
$result .= $actual_word . ' ';
$already[] = $actual_word;
}
}
}
$result = rtrim($result);
//would result in hansgrohe focus küchenarmatur metris
echo $result;
UPDATE2:
If you want to know number of occurences of each word.
<?php
$keywords = "hansgrohe,hansgrohe focus,küchenarmatur,hansgrohe metris";
$arr = explode(",", $keywords);
$already = [];
$nrwords = [];
$result = '';
foreach($arr as $word) {
$subword = explode(" ", $word);
foreach($subword as $actual_word) {
if (!in_array($actual_word, $already)) {
$result .= $actual_word . ' ';
$already[] = $actual_word;
$nrwords[$actual_word] = 0;
}
$nrwords[$actual_word]++;
}
}
$result = rtrim($result);
//would result in hansgrohe focus küchenarmatur metris
echo $result;
//would show how many of each word that exists
echo '<pre>';
print_r($nrwords);
echo '</pre>';
Hello I have a problem with this function I want to show the result of the function to put in a variable and send it to the database but it does not show me anything you can see in the example in the Second Block when I added echo its show me but I don't know how to get that result out I did use return but it gave a different result
$fullname = "Ayoub Chafik" ;
function orderID($data){
$AKK = "AK". date('YmdHis');
$string = strtoupper($data);
$strs=explode(" ",$string);
foreach($strs as $str)
$str[0];
}
// I want to see resulte here of this function
echo orderID($fullname) ;
?>
This is the second Block
<?php
$fullname = "Ayoub Chafik" ;
function orderID($data){
echo $AKK = "AK". date('YmdHis');
$string = strtoupper($data);
$strs=explode(" ",$string);
foreach($strs as $str)
echo $str[0];
}
echo orderID($fullname) ;
?>
As I explained in comment you store it in a variable and return it. Check below example. Also it is a good practice to open the {} even its only one line for more readability.
$fullname = "Ayoub Chafik" ;
function orderID($data) {
$string = strtoupper($data);
$strs = explode(" ", $string);
$results = '';
foreach($strs as $str) {
$results .= $str[0];
}
return $results;
}
echo orderID($fullname) ;
Some examples varying output based on your code sample.
$fullname = "Ayoub Chafik";
function orderID($data){
$string = strtoupper($data);
$strs=explode(" ",$string);
foreach($strs as $str) {
return $str;
}
}
echo orderID($fullname) ;
// output "AYOUB"
function _orderID($data){
$return = false;
$string = strtoupper($data);
$strs=explode(" ",$string);
foreach($strs as $str) {
$return = $str;
}
return $return;
}
echo _orderID($fullname) ;
// output "CHAFIK"
function _orderID_($data){
$return = [];
$string = strtoupper($data);
$strs=explode(" ",$string);
foreach($strs as $str) {
array_push($return,$str);
}
return json_encode($return);
}
echo _orderID_($fullname) ;
// output ["AYOUB","CHAFIK"]
check the above examples on PHP SandBox
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);
So I am trying to tokenizes the entire string based on the space and then put those tokens into different groups based on length of those tokens. I got how to split a string by space but I am stuck on put them into different group based on the length. For example, I have a string
Hello world, this is a test
So after split that string by space, I want to check the length of each token and then put them into different group like
Group 1: a
Group 2: is
Group 3: test, this
Group 4: hello, world
This is my code so far:
$strLength = count($string);
$stringSpl = explode(" ", $string);
if ($strLength <= 2) { //Here I try to check if the length is less than or equal 2 then place it into group 1
echo "Group 1: ";
foreach ($stringSpl as $key) {
echo $key . "<br/>";
}
}
Any help would be great! Thank you!
You're almost there, instead of trying to figure out the count, use the actual count of letters in each string/word, using strlen():
$words = explode(" ", $s);
$a = array();
foreach($words as $word){
$a["Group " . strlen($word)][] = $word;
}
print_r(array_reverse($a));
Example/Demo
You can simply use str_word_count function along with simple foreach and strlen like as
$str = "Hello world, this is a test";
$str_arr = str_word_count($str,1);
$result = array();
foreach($str_arr as $v){
$result["Group ".strlen($v)][] = $v;
}
print_r($result);
Demo
How about this? Above answers are great enough, but this is easy
<?
$string = "Hello world, this is a test";
$strings = array();
$stringSpl = explode(" ", $string);
foreach ($stringSpl as $key) {
$strings[strlen($key)][] = $key;
}
$idx = 1;
foreach ($strings as $array) {
echo "group ".($idx++).": ";
foreach ($array as $key) {
echo $key." ";
}
echo "<br>";
}
?>
Try this
$str = "Hello world, this is a test";
$str_arr = str_word_count($str,1);
$result = array();
$i=1;
foreach($str_arr as $v){
$result["Group ".strlen($v)][] = $v;
}
$n=count($result);
echo "<br/>";
$result_array=array_reverse($result);
foreach($result_array as $key=>$value)
{$gorup_value="";
echo $key.' ' ;
$count=count($value);
$i=1;
foreach($value as $key1=>$value1)
{
$gorup_value .= $value1.',' ;
}
echo rtrim( $gorup_value , ',');
echo "<br/>";
}
Now Edited then Answer Use this
I need to replace and concat some values in a random string, i store the values in an array.
I.e.
$search = array('dog', 'tree', 'forest', 'grass');
$randomString = "A dog in a forest";
If one or more array values matches the random string then i need a replace like this:
$replacedString = "A #dog in a #forest";
Can someone help me?
Thx.
foreach (explode(' ', $randomString) as $word) {
$replacedString .= in_array($word, $search) ? "#$word " : "$word ";
}
echo $replacedString; // A #dog in a #forest
foreach($search as $word)
{
$randomString = str_replace($word,"#".$word,$randomString);
}
Not sure if I understand what you're trying to do correctly but have a look at str_replace() function
and try something like
foreach($search as $string)
{
$replacement[] = "#".$search;
}
$new_string = str_replace($search, $replacement, $randomString);
This should work for you:
$words = explode(" ", $randomString);
foreach($words as $word){
if(in_array($word, $search)){
$word = "#$word";
}
}
$replacedString = implode(" ", $words);