won't remove spaces in string - php

I'm taking input from textarea form and put it in the long line.
Input is like this:
Country: France
City: Paris
Street: Champ
Then put it in the long line:
$line = $_POST['input'];
now, I need to replace spaces and new lines with <SP> and <BR>, so I do this:
$line = str_replace(" ","&ltSP&gt",$line);
$line = str_replace("\n","&ltBR&gt",$line);
but I get this:
Country:<SP>France <BR> <BR>City:<SP>Paris <BR> <BR>Street:<SP>Champ
Now, if insted of \n I tried this:
$line = str_replace("\r","&ltBR&gt",$line);
I get similar result. If I do them both i Get similar results which obviously has some spaces in it. So Then I do this:
$line = str_replace(" ","",$line);
but it stays the same.
My whole code is:
$line = str_replace(" ","&ltSP&gt",$line);
$line = str_replace("\n","&ltBR&gt",$line);
$line = str_replace(" ","",$line);
echo $line;
How to remove spaces in this case?
Edit:
I did bin2hex and found out that the space is actually carriage return \r.
So this is the solution:
$line = str_replace("\r","",$line);
Why did \r behave like space in this case?

the comments will probably suffice but I thought I'd share this snippet, which given your example I had a punt at what you are trying to achieve.
<?php
// example string data
$str = "key1 value1 key2 value2 key3 value3";
// clean string
$str = str_replace("&nbsp", " ",$str);
$str = str_replace("\n", " ", $str);
$str = str_replace("\r", " ", $str);
$arr = explode(" ", $str);
$out = "<ul>";
$cnt = 1;
foreach($arr as &$val) {
if ($cnt++ % 2 == 0) {
continue;
} else {
$out = $out . "<li>" . $val . ": " . current($arr) . "</li>";
}
}
$out = $out . "</ul>";
echo $out;
// output source
// <ul><li>key1: value1</li><li>key2: value2</li><li>key3: value3</li></ul>
?>

Related

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

Implode and Explode Array then wrap it inside a sample data

I have a string that looks like this:
$str = "Col1, Col2, Col3";
My question is how can I make it look like this
FORMAT(SUM('Col1'),2),FORMAT(SUM('Col2'),2),FORMAT(SUM('Col3'),2)
I am trying to use implode and explode but it's not working for me.
Here is my attempt:
$sample = "Col1, Col2, Col3";
$test = explode(",", $sample);
$test = "'" . implode("', FORMAT(SUM('", $test) . "), 2";
$sample = "Col1,Col2,Col3";
$test= explode(',',$sample);
$_test = '';
foreach($test as $t){
$_test .= "FORMAT(SUM('$t'),2),";
}
$_test = rtrim($_test,',');
I dont know if you can achiev this using explode, but you for sure can using a foreach loop.
$sample = 'Col1,Col2,Col3';
$result = '';
$parts = explode(',', $sample);
foreach ($parts as $part) {
$result .= 'FORMAT(SUM(' . $part . '), 2)';
$result .= (end($parts) !== $part) ? ', ' : '';
}
This runs over each part of the exploded array and adds the desired string plus a comma if its not the last element.
You can also use array_walk to achieve the requested result:
$sample = 'Col1,Col2,Col3';
$parts = explode(',', $sample);
$str = '';
array_walk($parts, function ($element) use (&$str) {
$str .= 'FORMAT(SUM(' . $element . '), 2), ';
});
$result = rtrim($str, ', ');

Removing last comma in the foreach query in php mysql

Im using a foreach loop to echo out some values from my database and seperating each of them by commas but last comma how we can remove
echo $string='"paymentmethods":';
echo $string='"Bank":[';
$sql2 = "SELECT * FROM paymentmethods where cid=587 ";
$query = $this->db->query($sql2);
foreach ($query->result() as $row){
echo '{';
echo $string = 'accname:'.$row->acc.',' ;
echo $string = 'country:'.$row->IBAN.',' ;
echo $string = 'Iban:'.$row->Bankname.',' ;
echo $string = 'Bankname:'.$row->Bankname.',' ;
echo $string = '},';
}
echo $string = '],';
"paymentmethods":"Bank":[{accname:0034430430012,country:AE690240002520511717801,Iban:ARABIC BANK NAME,Bankname:ARABIC BANK NAME,},{accname:0506796049,country:DE690240002520511717801,Iban:ARABIC BANK NAME,Bankname:ARABIC BANK NAME,},]
Here see the comma is repeating after the name ends. and also after the end of brackets
The comma is there because you have written it in your code. Change the lines to this :
// same as above
echo $string = 'Bankname:'.$row->Bankname. ;
echo $string = '}';
}
echo $string = ']';
a common way to do this is to do this way :
$sep = '';
$result = '';
foreach($myarray as $value) {
$result .= $sep.$value;
$sep = ',';
}
this way, you don't have a beginning or ending comma.
But as comments say, you are doing a "json_encode" by yourself... you should use json_encode / decode instead.

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