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);
Related
I have a simple form where I can enter a sentence. When I submit the form I want to shuffle the words (not characters). This is what I did so far, but it's not mixing the words:
if (isset($_POST['sentence'])) {
$original_sentence = $_POST['sentence'];
} else {
die ('Give me a sentence!');
}
$words = explode( " / ", $original_sentence );
foreach($words as $word) {
array_rand($words);
echo $word;
}
you can explode, shuffle and implode:
$original_sentence = "i am a simple sentence";
$words = explode( " ", $original_sentence );
shuffle($words);
echo implode(" ",$words);
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
http://php.net/manual/en/function.shuffle.php
I need to edit all odd words to upper case.
Here is sample of imput string:
very long string with many words
Expected output:
VERY long STRING with MANY words
I have this code, but it seams to me, that I can do it in better way.
<?php
$lines = file($_FILES["fname"]["tmp_name"]);
$pattern = "/(\S[\w]*)/";
foreach($lines as $value)
{
$words = NULL;
$fin_str = NULL;
preg_match_all($pattern, $value, $matches);
for($i = 0; $i < count($matches[0]); $i = $i + 2){
$matches[0][$i] = strtoupper($matches[0][$i]);
$fin_str = implode(" ", $matches[0]);
}
echo $fin_str ."<br>";
P.S. I need to use only preg_match function.
Here's a preg_replace_callback example:
<?php
$str = 'very long string with many words';
$newStr = preg_replace_callback('/([^ ]+) +([^ ]+)/',
function($matches) {
return strtoupper($matches[1]) . ' ' . $matches[2];
}, $str);
print $newStr;
// VERY long STRING with MANY words
?>
You only need to match the repeating pattern: /([^ ]+) +([^ ]+)/, a pair of words, then preg_replace_callback recurses over the string until all possible matches are matched and replaced. preg_replace_callback is necessary to call the strtoupper function and pass the captured backreference to it.
Demo
If you have to use regular expressions, this should get you started:
$input = 'very long string with many words';
if (preg_match_all('/\s*(\S+)\s*(\S+)/', $input, $matches)) {
$words = array();
foreach ($matches[1] as $key => $odd) {
$even = isset($matches[2][$key]) ? $matches[2][$key] : null;
$words[] = strtoupper($odd);
if ($even) {
$words[] = $even;
}
}
echo implode(' ', $words);
}
This will output:
VERY long STRING with MANY words
You may don't need regex simply use explode and concatenate the string again:
<?php
function upperizeEvenWords($str){
$out = "";
$arr = explode(' ', $str);
for ($i = 0; $i < count($arr); $i++){
if (!($i%2)){
$out .= strtoupper($arr[$i])." ";
}
else{
$out .= $arr[$i]." ";
}
}
return trim($out);
}
$str = "very long string with many words";
echo upperizeEvenWords($str);
Checkout this DEMO
I have a csv file that contains company names. I would want to match it against my database. In order to have a cleaner and nearer matches, I am thinking of eliminating some company suffixes like 'inc', ' inc', ', inc.' or ', inc'. Here's my sample code:
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc."," Inc.",", Inc.",", Inc"," Inc");
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
$string = preg_replace($wordlist, '', $string);
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;
My problem here is that the 'inc.' doesn't get removed. I'm guessing it has something to do with the preq_quote. But I just can't figure out how to solve this.
Try this :
$string = 'Inc incorporated inc.';
$wordlist = array("Inc","inc.");
foreach ($wordlist as $word) {
$string =str_replace($word, '', $string);
}
echo $string;
OR
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc.");
$string = str_replace($wordlist, '', $string);
echo $string;
This will output as 'corporated'...
If you want "Incorporated" as result, make the "I" is small.. and than run my above code (first one)...
Try this. It may involve type juggling at some point, but will have your desired result
$string = 'Inc Incorporated inc.';
$wordlist = array('Inc', 'inc.');
$string_array = explode(' ', $string);
foreach($string_array as $k => $a) {
foreach($wordlist as $b) {
if($b == $a){
unset($string_array[$k]);
}
}
$string_array = implode('', $string_array);
You can use this
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc "," inc.");
$foo = str_replace($wordlist, '', $string);
echo $foo;
Run this code here
This will work for any number of elements in array...
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc");
foreach($wordlist as $stripped)
$string = preg_replace("/\b". preg_quote($stripped,'/') ."(\.|\b)/i", " ", $string) ;
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;
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);
}
I want to know how to count to the second space then return to the newline with php , for example :
the text: "How are you?"
becomes
"how are
you?"
how can I do that with php?
thank you
Here is a function that uses strpos to return the position of the Nth specified character.
http://us2.php.net/manual/en/function.strpos.php#96576
Find that position, then do a substr_replace to put a \n in that spot.
print preg_replace('/((:?\S+\s){2})/i', "\$1\r\n", "How are you?" );
function addNlToText($text) {
$words = explode(' ', $text);
$out = '';
foreach ($words as $key => $value) {
$out .= $value;
if ($key % 2 === 0) {
$out .= "\n";
} else {
$out .= ' ';
}
}
return trim($out);
}
That's dirty, but it does what you ask...
$text = 'Hello, how are you?';
addNlToText($text); // "Hello, how\nare you?"
$text = 'Hello';
addNlToText($text); // "Hello"
$text = 'Hello what is going on?';
addNlToText($text); // "Hello what\nis going\non?"
I wonder if you are not after something like the wordwrap function?
http://www.php.net/wordwrap
Try this:
<?php
$mystring = 'How are you?';
$findme = ' ';
$pos = strpos($mystring, $findme);
$pos = strpos($mystring, $findme, $pos+1);
$mystring = substr_replace($mystring, '<br>', $pos, 0);
echo $mystring;
?>
You can do it using javascript, Is it ok using javascript?