format explode data after first piece with foreach - php

What I have is this array:
$l = "apple,orange,tomato,banana,carrot,celery";
What i'm trying to do is something along these lines:
apple OR orange OR tomato OR banana OR carrot OR celery
I've gotten this far:
$l = explode(",", $l);
if (count($l) > 1){
foreach ($l as $s){
echo " OR " . $s;
}
}
Doing it this way puts OR in front of all the pieces of the array:
OR apple OR orange OR tomato OR banana OR carrot OR celery
What would be the proper way to count the first piece, then append to all the additional pieces?

try this:
$array = explode(",", $l);
echo implode(" OR ", $array);
Or in one liner:
echo implode(" OR ", explode(",", $l));

Use str_replace:
$string = 'oranges,apples,pineapple';
echo str_replace(',', ' OR ', $string);
// Outputs: oranges OR apples OR pineapple

one line skill
$array = implode (' OR ', explode (',', $array));

You may try with this :)
echo preg_replace('/,/', " OR ", "apple,orange,tomato,banana,carrot,celery");

or in case you want to treat the information :
$pieces = explode (',', $array);
$result = '';
$i = 0;
foreach ($pieces as $p) {
$i++;
if ($p === 'banana') // in case you hate banana
continue;
$result .= $p;
if ($i != count($pieces))
$result .= ' OR ';
}

Related

PHP array split into custom sentence?

I have a PHP array and I want to split it into a custom sentence.
$array = array('apple','blue','red','green');
I want the output below:
apple
apple blue
apple blue red
apple blue red green
You could try this simple solution
$array = array('apple','blue','red','green');
$sentence = "";
foreach($array as $key) {
if($sentence === ""){
$sentence = $key;
}
else{
$sentence = $sentence." ".$key;
}
echo $sentence;
echo "</br>";
}
Pretty simple lightweight solution
$array = array('apple','blue','red','green');
$str = '';
foreach($array as $item) {
$str = $str . ' ' . $item;
echo(ltrim($str) . '<br>');
}
Use for-loop with array_slice to Extract a slice of the array each time, And use implode(glue, pieces) to join the values of the array with a space.
$array = array('apple','blue','red','green');
for ($i=1; $i <= count($array) ; $i++) {
echo implode(' ', array_slice($array, 0, $i))."</br>";
}
Prints:
apple
apple blue
apple blue red
apple blue red green
This is very simple
$array = array('apple','blue','red','green');
$new = "";
for($i=0; $i<sizeof($array); $i++) {
for($j=0; $j<=$i; $j++){
$new .= $array[$j]." ";
}
$new .= "<br>";
}
echo $new;

How to reformat a string of words with commas/ampersands in PHP

I am trying to write some PHP code that will separate words when the are two with "&" and a comma when they are three and the last two with "&"
Something like this
$string = "stack over flow";
Print on screen like this "stack, over & flow";
Hope you noticed the comma and the ampersand.
Then when they are two words
$string = "stack overflow";
print like this echo "stack & overflow";
Here is my code I have been trying, but I am not getting it right:
$string = '1,2';
$list = explode(',',$string);
foreach($list as $row) {
if($list = 2) {
echo ''.$row.' &';
}
}
This should take into account the possibilities of one or more words. If there is more than one word, just remove the last word (using array_pop()) and implode() with , the remaining words.
If there is only 1 word, the result is the same as the original string...
$string = "stack over";
$list = explode(" ", $string);
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = implode(", ", $list) . " & {$last}";
}
else {
$result = $string;
}
To add anchor tags to each word...
$list = explode(" ", $string);
$aTag = '<a href="#">';
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = $aTag.
implode("</a>, {$aTag}", $list) . "</a> & {$aTag}{$last}</a>";
}
else {
$result = $aTag.$string."</a>";
}
echo $result;
thanks Nigel Ren.. you code was really helpfully
but their a correction i made.Here
$string = "stack over flow";
$list = explode(" ", $string);
$aTag = '<a href="#">';
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = $aTag.
implode('</a>, '.$aTag.'', $list) . "</a> & {$aTag}{$last}</a>";
}
else {
$result = $aTag.$string."</a>";
}
echo $result;
thanks

Array value from variable

Could somebody explaind me ***why array count is not 2
$value = '"305", "112", ';
//remove last comma and space
echo $value = rtrim($value, ', ');
echo '<br>';
$value = array($value);
echo $array_length = count($value); //***
You should use explode function to get array like the following code :
$value = '"305", "112"';
$value = rtrim($value, ', ');
echo '<br>';
$value = explode(',',$value);
echo $array_length = count($value);
you can use explode() to get it.
$value = '"305", "112", ';
//remove last comma and space
echo $value = rtrim($value, ', ');
echo '<br>';
$value = explode(',',$value);
echo $array_length = count($value);
you can also do this if you want to create an array from that these type of strings and do array count.
$arr = array_filter(array_map('trim', str_getcsv($value)));
print_r($arr);
echo count($arr);
when you are creating an array with array($value), the entire value of $value counted as a single element of an array. Thats why you are getting count($value) not equal to 2.

How can I put '-' between words in this code php?

Below code will echo like this
('nice apple'),(' nice yellow banana'),(' good berry ')
what I need to do is that I need them to be like this
('nice-apple'),(' nice-yellow-banana'),(' good-berry ')
The challenge is that I could not touch $str, and then I need to use '-' to connect words if there is space between them, If use str_replace space, it will be something like ----nice-apple-. how can I achieve something like this ('nice-apple'), appreciate.
<?php
$str="nice apple,
nice yellow banana,
good berry
 ";
echo $str = "('" . implode("'),('", explode(',', $str)) . "')";
?>
Try str_replace
$str="nice apple,
nice yellow banana,
good berry
";
$str = array_map(function($dr){ return preg_replace('/\s+/', '-', trim($dr));},explode(',',$str));
$str = implode(',',$str);
echo $str = "('" . implode("'),('", explode(',', $str)) . "')";
Output:
('nice-apple'),('nice-yellow-banana'),('good-berry')
Its bit tricky. Try with -
$str="('nice apple'),(' nice yellow banana'),(' good berry ')";
$v = explode(',', $str); // generate an array by exploding the string by `,`
foreach($v as $key => $val) {
$temp = trim(str_replace(["(", "'", ")"], "", $val)); //remove the brackets and trim the string
$v[$key] = "('".str_replace(" ", "-", $temp)."')"; // place the `-`s
}
$new = implode(",", $v); // implode them again
var_dump($new);
you need to get rid of the new lines first then it'll work.
<?php
$str="nice apple,
nice yellow banana,
good berry
";
$arr = explode(',', str_replace([ "\r\n", "\n" ], "", $str));
$arrCount = sizeOf($arr);
for($x = 0; $x < $arrCount; $x++) {
while (preg_match('/(\w)\s(\w)/', $arr[$x])) {
$arr[$x] = preg_replace('/(\w)\s(\w)/', '$1-$2', $arr[$x]);
}
}
echo $str = "('" . implode("'),('", $arr) . "')";
?>
('nice-apple'),(' nice-yellow-banana'),(' good-berry ')

remove word from string by position from input

EXAMPLE:
input = 2
text = aa bb cc
Will become: aa cc
The input for position is $_POST['position']
i have
$words = explode(" ", $_POST['string']);
for ($i=0; $i<count($words); $i++){
echo $words[$i] . " ";
}
$to_remove = 2;
$text = "aa bb cc";
$words = explode(' ', $text);
if(isset($words[$to_remove -1])) unset($words[$to_remove -1]);
$text = implode(' ', $words);
Pulling out the big guns REGEX !!!
$string = 'aa bb cc dd';
$input = 2;
$regex = $input - 1;
echo preg_replace('#^((?:\S+\s+){'.$regex.'})(\S+\s*)#', '$1', $string);
Output: aa cc dd
Foreach loops tend to make it a little easier to understand (IMO). Looks cleaner too.
$pos = 2;
$sentence = explode(" ", $_POST['string']);
foreach ($sentence as $index => $word) {
if ($index != $pos - 1) {
$result .= $word . ' ';
}
}
echo $result;
This sounds like a homework question. I'll take a stab at it though:
Code:
<?php
$string = trim($_POST['string']);
$parts = explode(" ", string);
$newString = "";
$position = intval($_POST['position']);
for($a = 0; $a < count($parts); $a++) {
if($a != $position) { // or $a != ($position - 1) depending on if you passed in zero based position
$newString = $newString . $parts[$a] . " ";
}
}
$newString = trim($newString);
echo "Old String: " . $string . "<br />";
echo "New String: " . $newString;
?>
Output:
Old String: aa bb cc
New String: aa cc
$input = 2;
$words = explode(" ", $_POST['string']);
unset($words[$input-1]);
$words = implode(" ", $words);
echo $words;

Categories