Convert the string in 123, 234, 345 etc. format - php

I have a string like below
$string = "hi hello how are you ? hope you";
I need result in array like below
hi hello how
hello how are
how are you
are you hope
you hope you.
I tried something like below
$exp = explode(" ",$string);
foreach($exp as $lol)
{
//now i have no idea what to do..some 1 guide me please.
}

Try this use the array_shift and run the loop two times.
Note: Read the comment in the answer as i explain there why i wrote it this way.
<?php
$string = "hi hello how are you hope you";
$exp = explode(" ",$string);
for ($i=0; $i<(count($exp)+3);$i++)//as you want to print three value in
//each loop your loop should run three more time than
//the number of element you got in your original array
{
echo '<br/>';
for($k=0;$k<3;$k++)
{
echo ' ';//added the space to see
print_r($exp[$k]);//to see the result
}
$value= array_shift($exp);//after printing the result remove the
//first element from the array. so this will remove the first elemenet after
//each result.
}
Your Result will look like this
hi hello how
hello how are
how are you
are you hope
you hope you

This code sample give 2 levels .No of foreach is the no of words.
$vari = "hai hello how?";
$vari = str_replace("?", "", $vari);
$vars = explode(" ", $vari);
$varp = $vars;
foreach ($vars as $p_i=>$p_v){
foreach($varp as $c_i=>$c_v){
if($p_i!=$c_i){
echo $p_v." ".$c_v."<br/>";
}
}
}
RESULT
hai hello
hai how
hello hai
hello how
how hai
how hello
You can put foreach inside another foreach to get more words.

Related

Replacing string except certain parts

I'm writing a PHP app, and I have an input string in the form
Hello world. Hello [fbes_keep]world[/fbes_keep].
And a new string in the form
Hallo welt. Hello.
What I want it for the input string to be replaced by the new string, except the parts in the [fbes_keep] tags, so the output is
Hallo welt. Hello [fbes_keep]world[/fbes_keep].
My current approach involves using the finediff library but overriding the delete opcodes to look for the fbes tags. I asked a question about this yesterday, but I feel I may have run into the XY problem. Is there a better way?
Edit: Gist containing current (non-functional) code and real-world test case.
Maybe this is not the most elegant way how do I did it, but I've tested it, and it do the job:
$expression = 'world';
$newExpression = 'welt';
$str = 'Hello world. Hello [fbes_keep]world[/fbes_keep]. Here are some other world, and [fbes_keep]other[/fbes_keep] word in fbes.';
$pattern = '/\[fbes_keep\].*?\[\/fbes_keep\]/i';
$fbKepps = [];
preg_match_all($pattern, $str, $fbKepps);
$others = preg_split($pattern, $str);
$result = '';
$i = 0;
foreach ($others as $other) {
$result .= preg_replace('/' . addslashes($expression) . '/', $newExpression, $other);
$i++;
if ($i < count($others)) {
$result .= $fbKepps[0][$i - 1];
}
}
echo $result;
OUTPUT
Hello welt. Hello [fbes_keep]world[/fbes_keep]. Here are some other welt, and [fbes_keep]other[/fbes_keep] word in fbes.
My ideia is to split the string by [fbes_keep]...[/fbes_keep], but before store them in an array. Then iterate through all the rest, change the world to welt then concat the next fbes_keep and so on...
It keeps everything wher [fbes_keep]anything[/fbes_keep] and there are multiple fbes_keep can be in string with other words too.

How to extract certain text from a string

I've string like this:
hi my best friend #John How Are You?
I want to extract the name from the string:
john
This string has only one name it can be any number of names the string will have. I want to fetch the string between # and [space].
I've tried using explode() and foreach() loop, but I'm not able to get this value.
$text = "hi my best friend #John How Are You?";
preg_match_all("/(#\w+)/", $text, $matches);
var_dump( $matches );
try this
<?php
$string="hi my best friend #John How Are You?";
preg_match('/(?<=hi my best friend #)\S+/i', $string, $match);
echo $match[0];
Output
Jhon
Try this,
$string = "hi my best friend #John How Are You?";
$arr = explode(" ",$string);
foreach($arr as $val){
if (strpos($val,'#') !== false) {
$result = str_replace("#","",$val);
}
}
echo $result;
The regular expression will do fine but if you still want to do this using explode() and loop you may try the following code :-
$str="Hello my name is #John and this is my friend #julia";
$exp=explode(" ",$str);//exploding string from space
foreach($exp as $key=>$val){
if(strpos($val,"#")===false){continue;
}
else{$new[$k]=str_replace("#","",$val);}
}
print_r($new);
Hope this might help you.
Here is a quick working example
$string = "hi my best friend #John How Are You?";
$explodedstring = explode('#', $string);
$explodedforspace = explode(' ',$explodedstring[1]);
echo $explodedforspace[0];
?>

Add numbers in a string using PHP stored in MySQL DB

I have a string save in mysql database like this:
"This is the total 98+84+67"
And I want the string to look like this when I display in my page using php:
"This is the total 249"
Is this possible without adding first the numbers before inserting in the database. Only add when I display the string to my site?
Please help!
$string = "This is the total 98+84+67 of the numbers 98, 84 and 67 if we add.";
preg_match("/[\d]+\+[\d+]+/",$string,$matches);
$numbers = explode("+",$matches[0]);
$sum = array_sum($numbers);
print preg_replace("/[\d]+\+[\d+]+/",$sum,$string);
Demo
This code may help you, you should be sure that the expression in the end doesn't have any space
<?php
$str = "This is the total 98+84+67";
function calculate($str)
{
$exp = preg_replace('/[^0-9+]+/', "", $str);
eval("\$result = " . $exp . ";");
$str = str_replace($exp, $result, $str);
return $str;
}
echo calculate($str);
?>

PHP searching/formatting string dynmically

I have multiple different db strings, one for example is:
"Apples,Apples,Apples,Oranges,Apples,Oranges"
I want to represent each string dynamically as:
"I have Apples and Oranges. There are 6 in total."
Another string might be:
"Apples,Apples,Apples,Apples";
Should say:
"I have Apples. There are 4 in total."
How would I script this in PHP? Ty for help!
<?php
$str = 'Apples,Apples,Apples,Oranges,Apples,Oranges';
$arr = explode(',', $str);
echo 'I have '.implode(' and ', array_unique($arr))
. '. There are '.count($arr).' in total.';
This should be self explanatory but for reference see: explode, implode & array_unique
I made this test:
<?php
$data = "Apples,Apples,Apples,Oranges,Apples,Oranges";
$array = explode(",",$data); //array of elements
$count = count($array); //How many elements
$arr_unique = array_unique($array); //array of unique elements
echo "I have ".implode(" and ", $arr_unique). ". There are ".$count." in total.";
//var_dump($arr_unique); //For test
?>
PS: Check the fiddle: http://phpfiddle.org/main/code/3u4-e5v

string replace php - one word to more words

Hi all i need a particulary type of string replace in php.
I need to replace a word with two different others words.
For example: in the string "Hi mom, hi dad" i need to automatically replace the word "hi" with two other different, for example "mary" and "john". So if there is only one occurrence of "Hi" it replace only with "mary" but if there are more than one it uses all the association of words.
So, one word more replaces based on how many times the word occurrence.
Thanks to all who can help me!
preg_replace_callback lets you control each replacement.
You could accomplish this with multiple calls to preg_replace, specifying a limit of 1 for each call:
$string = "Hi mom, hi dad";
preg_replace('/hi/i', 'mary', $str, 1); // "mary mom, hi dad"
preg_replace('/hi/i', 'john', $str, 1); // "mary mom, john dad"
You could generalize this with something like the following. It takes a subject, a pattern, and 1 or more replacement words.
function replace_each($subject, $pattern, $replacement) {
$count = 0;
for ($i = 2; $i < func_num_args(); ++$i) {
$replacement = func_get_arg($i);
$subject = preg_replace($pattern, $replacement, $subject, 1, $count);
if (!$count)
// no more matches
break;
}
return $subject;
}
$string = preg_replace_each("Hi mom, hi dad", "/hi/i", "mary", "john");
echo $string; // "mary mom, john dad"
preg_replace_callback is one way, another is to utilize $limit and $count parameters of preg_replace (see manpage )
$str = "hi foo hi bar hi baz hi quux";
$repl = array('uno', 'dos', 'tres');
do{
$str = preg_replace('~hi~', $repl[0], $str, 1, $count);
$repl[] = array_shift($repl); // rotate the array
} while($count > 0);
I'm not sure if there is a really easy way to do it but take a look at this piece of code i just wrote. This should do the trick for you :)
<?php
class myReplace{
public $replacements = array();
protected $counter = 0;
public function __construct($replacements) {
// fill the array with replacements
$this->replacements = $replacements;
}
public function test($matches) {
// if you want you could do something funky to the matches array here
// if the key does not exists we are gonna start from the first
// array element again.
if(!array_key_exists($this->counter, $this->replacements)) {
$this->counter = 0;
}
// this will return your replacement.
return $this->replacements[$this->counter++];
}
}
// Instantiate your class here, and insert all your replacements in sequence
$obj = new myReplace(array('a', 'b'));
// Lets start the replacement :)
echo preg_replace_callback(
"/hi/i",
array($obj, 'test'),
"Hi mom, hi dad, hi son, hi someone"
);
?>
This code will result in:
a mom, b dad, a son, b someone

Categories