Exploding a string results in weird array - php

I have a string that looks like this "thing aaaa" and I'm using explode() to split the string into an array containing all the words that are separated by space. I execute something like this explode (" ", $string) .
I'm not sure why but the result is : ["thing","","","","aaaa"]; Does anyone have an idea why I get the three empty arrays in there ?
EDIT : This is the function that I'm using that in :
public function query_databases() {
$arguments_count = func_num_args();
$status = [];
$results = [];
$split =[];
if ($arguments_count > 0) {
$arguments = func_get_args();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arguments));
foreach ($iterator as $key => $value) {
array_push($results, trim($value));
}
unset($value);
$filtered = $this->array_unique_values($results, "String");
foreach ($filtered as $key => $string) {
if (preg_match('/\s/',$string)) {
array_push($split, preg_split("/\s/", $string));
} else {
array_push($split, $string);
}
}
unset($string);
echo "Terms : ".json_encode($split)."<br>";
foreach ($filtered as $database) {
echo "Terms : ".json_encode()."<br>";
$_action = $this->get_database($database);
echo "Action : ".json_encode($_action)."<br>";
}
unset($database);
} else {
return "[ Databases | Query Databases [ Missing Arguments ] ]";
}
}
It might be something else that messes up the result ?!

If you are looking to create an array by spaces, you might want to consider preg_split:
preg_split("/\s+/","thing aaaa");
which gives you array ("thing","aaaa");
Taken from here.

try this:
$str = str_replace(" ", ",", $string);
explode(",",$str);
This way you can see if it is just the whitespace giving you the problem if you output 4 commas, it's because you have 4 whitespaces.

As #Barmar said, my trim() just removes all the space before and after the words, so that is why I had more values in the array than I should have had.
I found that this little snippet : preg_replace( '/\s+/', ' ', $value ) ; replacing my trim() would fix it :)

Related

check a string contains any word from array

i have a set of predefined array contains strings and words.I am trying to check whether my string contains at least one word from that array.
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code testy';//code is already in that array
i tried many ways,but not correct solution
first method
$i = count(array_intersect($array, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $string))));
echo ($i) ? "found ($i)" : "not found";
second method
if (stripos(json_encode($array),$string) !== false) { echo "found";}
else{ echo "not found";}
I suppose you are looking for a match which is any of the words.
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code|testy';
foreach ($array as $item ) {
if(preg_match("/\b{$string}\b/i", $item)) {
var_dump( $item );
}
}
You have to iterate over the array and test each one of the cases separately, first 'code', then 'testy', or whatever you want. If you json_encode, even if you trim both of strings to do this comparaison, the return will be not found.
But in the first string if you had like this
$array = array("PHP code testy Sandbox Online","abcd","defg" );
$string = 'code testy';//code is already in that array
you will get surely a "found" as return.
if (stripos(trim(json_encode($array)),trim($string)) !== false) { echo "found";}
else{ echo "not found";}
You could use explode() to get an array from the strings and then go through each of them.
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code testy';
foreach(explode(' ', $string) as $key => $value) {
foreach($array as $arrKey => $arrVal) {
foreach(explode(' ', $arrVal) as $key => $str) {
if ($value == $str) {
echo $str . ' is in array';
}
}
}
}

implode() string, but also append the glue at the end

Trying to use the implode() function to add a string at the end of each element.
$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("#txt.att.net,", $array);
print($attUsers);
Prints this:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132
How do I get implode() to also append the glue for the last element?
Expected output:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132#txt.att.net
//^^^^^^^^^^^^ See here
There is a simpler, better, more efficient way to achieve this using array_map and a lambda function:
$numbers = ['9898549130', '9898549131', '9898549132'];
$attUsers = implode(
',',
array_map(
function($number) {
return($number . '#txt.att.net');
},
$numbers
)
);
print_r($attUsers);
This seems to work, not sure its the best way to do it:
$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("#txt.att.net,", $array) . "#txt.att.net";
print($attUsers);
Append an empty string to your array before imploding.
But then we have another problem, a trailing comma at the end.
So, remove it.
Input:
$array = array('9898549130', '9898549131', '9898549132', '');
$attUsers = implode("#txt.att.net,", $array);
$attUsers = rtrim($attUsers, ",")
Output:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132#txt.att.net
This was an answer from my friend that seemed to provide the simplest solution using a foreach.
$array = array ('1112223333', '4445556666', '7778889999');
// Loop over array and add "#att.com" to the end of the phone numbers
foreach ($array as $index => &$phone_number) {
$array[$index] = $phone_number . '#att.com';
}
// join array with a comma
$attusers = implode(',',$array);
print($attusers);
$result = '';
foreach($array as $a) {
$result = $result . $a . '#txt.att.net,';
}
$result = trim($result,',');
There is a simple solution to achieve this :
$i = 1;
$c = count($array);
foreach ($array as $key => $val) {
if ($i++ == $c) {
$array[$key] .= '#txt.att.net';
}
}

PHP - Add value to comma based string/array

I am storing some data in my database in a comma based string like this:
value1, value2, value3, value4 etc...
This is the variables for the string:
$data["subscribers"];
I have a function which on users request can remove their value from the string or add it.
This is how I remove it:
/* Remove value from comma seperated string */
function removeFromString($str, $item) {
$parts = explode(',', $str);
while(($i = array_search($item, $parts)) !== false) {
unset($parts[$i]);
}
return implode(',', $parts);
}
$newString = removeFromString($existArr, $userdata["id"]);
So in the above example, I am removing the $userdata['id'] from the string (if it exists).
My problem is.. how can I add a value to the comma based string?
Best performance for me
function addItem($str, $item) {
return ($str != '' ? $str.',' : '').$item;
}
You can use $array[] = $var; simply do:
function addtoString($str, $item) {
$parts = explode(',', $str);
$parts[] = $item;
return implode(',', $parts);
}
$newString = addtoString($existArr, $userdata["id"]);
function addToString($str, $item) {
$parts = explode(',', $str);
array_push($parts, $str);
return implode(',', $parts);
}
$newString = addToString($existArr, $userdata["id"]);

PHP Replacing Character Inside String With Variable

In few words, I am trying to replace all the "?" with the value inside a variable and it doesn't work. Please help.
$string = "? are red ? are blue";
$count = 1;
update_query($string, array($v = 'violets', $r = 'roses'));
function update_query($string, $values){
foreach ( $values as $val ){
str_replace('?', $val, $string, $count);
}
echo $string;
}
The output I am getting is: ? are red ? are blue
Frustrated by people not paying attention, I am compelled to answer the question properly.
str_replace will replace ALL instances of the search string. So after violets, there will be nothing left for roses to replace.
Sadly str_replace does not come with a limit parameter, but preg_replace does. But you can actually do better still with preg_replace_callback, like so:
function update_query($string, $values){
$result = preg_replace_callback('/\?/', function($_) use (&$values) {
return array_shift($values);
}, $string);
echo $string;
}
You forgot to set it equal to your variable.
$string = str_replace('?', $val, $string, $count);
You probably want to capture the return from str_replace in a new string and echo it for each replacement, and pass $count by reference.
foreach ( $values as $val ){
$newString = str_replace('?', $val, $string, &$count);
echo $newString;
}
This is the best and cleanest way to do it
<?php
$string = "? are red ? are blue";
$string = str_replace('?','%s', $string);
$data = array('violets','roses');
$string = vsprintf($string, $data);
echo $string;
Your code edited
$string = "? are red ? are blue";
update_query($string, array('violets','roses'));
function update_query($string, $values){
$string = str_replace('?','%s', $string);
$string = vsprintf($string, $values);
echo $string;
}
Ok guys here is the solution from a combination of some good posts.
$string = "? are red ? are blue";
update_query($string, array($v = 'violets', $r = 'roses'));
function update_query($string, $values){
foreach ( $values as $val ){
$string = preg_replace('/\?/', $val, $string, 1);
}
echo $string;
}
As mentioned, preg_replace will allow limiting the amount of matches to update. Thank you all.
You can solve this in two ways:
1) Substitute the question marks with their respective values. There are a hundred ways one could tackle it, but for something like this I prefer just doing it the old-fashioned way: Find the question marks and replace them with the new values one by one. If the values in $arr contain question marks themselves then they will be ignored.
function update_query($str, array $arr) {
$offset = 0;
foreach ($arr as $newVal) {
$mark = strpos($str, '?', $offset);
if ($mark !== false) {
$str = substr($str, 0, $mark).$newVal.substr($str, $mark+1);
$offset = $mark + (strlen($newVal) - 1);
}
}
return $str;
}
$string = "? are red ? are blue";
$vars = array('violets', 'roses');
echo update_query($string, $vars);
2) Or you can make it easy on yourself and use unique identifiers. This makes your code easier to understand, and more predictable and robust.
function update_query($str, array $arr) {
return strtr($str, $arr);
}
echo update_query(':flower1 are red :flower2 are blue', array(
':flower1' => 'violets',
':flower2' => 'roses',
));
You could even just use strtr(), but wrapping it in a function that you can more easily remember (and which makes sense in your code) will also work.
Oh, and if you are planning on using this for creating an SQL query then you should reconsider. Use your database driver's prepared statements instead.

String that looks like an array to a real array (PHP)

I've come up with this monstrosity :
echo $value;
And the result is this:
"_aaaaaaa","_bbbbbb","_cccccc","_dddddd"
This is i a string....but i want to make it look like this in end.
$value= array("_aaaaaaa","_bbbbbb","_cccccc","_dddddd");
I've tried everything.How can i make this string into an array like the above ?
Any help here ?
-Thanks
If I understand you correctly, $value = explode(',', $value); should turn this into an array.
Try as following:
$value= '"_aaaaaaa","_bbbbbb","_cccccc","_dddddd"';
$array = array_map(function($v) { return trim($v, '"'); }, explode(',', $value));
More simply:
$array = explode('","', trim($value, '"'));
Hope this help
$str = '"_aaaaaaa","_bbbbbb","_cccccc","_dddddd"';
$value = explode(',', $str);
foreach ($values as $val) {
$val = trim($val, '"');
}
Your question would need more specific description I guess what you are trying to achieve but if you have a string that contains values separated by , and surrounded with quotes then you want to do something like this:
$value = explode(',', $value);
foreach ($value as &$val) {
$val = trim($val, '"');
}

Categories