Transfer list in php in another list - php

I have a list of words for example this one
$words1="Les voitures Le compteur principal capteurs(gaz et l'éclairage) l'humidité L'extérieur"
and i want to have the list like this:
$words2="Les","voitures","Le","compteur","principal","capteurs(gaz","et","l'éclairage)","l'humidité","L'extérieur"
i did the split a string by string of the list using explode and then i did not find how to add the "," between the strings:
$text_list =explode(" ",$words1);

Try this: Online Test
First explode the string as " ", and then implode the using " , " and also add the " before and after implode.
$text_list = explode(" ",$words1);
echo $words2 = '"'.implode('","', $text_list).'"';
you will get:
"Les","voitures","Le","compteur","principal","capteurs(gaz","et","l'éclairage)","l'humidité","L'extérieur"
As per your requirement:
$words2 = explode(",", '"'.implode('","', $text_list).'"');
echo gettype($words2); //array
print_r of $words2:
Array
(
[0] => "Les"
[1] => "voitures"
[2] => "Le"
[3] => "compteur"
[4] => "principal"
[5] => "capteurs(gaz"
[6] => "et"
[7] => "l'éclairage)"
[8] => "l'humidité"
[9] => "L'extérieur"
)
Another way:
$words2 = array('"'.implode('","', $text_list).'"');
echo gettype($words2); //array
print_r of $words2:
Array
(
[0] => "Les","voitures","Le","compteur","principal","capteurs(gaz","et","l'éclairage)","l'humidité","L'extérieur"
)

If you're trying to make an array from the string, your approach is valid - just use the explode() function. But if you're trying to replace the space in the string with commas, you can use the str_replace() function.
$words1="Les voitures Le compteur principal capteurs(gaz et l'éclairage) l'humidité L'extérieur";
$commaSeparatedString = str_replace(' ', ', ', $words1);
Further, you can explode the result by space, to get each word with comma in a simple array.
$result = explode(' ', $commaSeparatedString);

Related

How to add double quotes around words-or-phrases-with-spaces-between-words?

Given the following string (Yes, STRING, not Array), I want to add double quotes around the names of countries.
$string = "Array ( [0] => Array ( [nicename] => Afghanistan [phonecode] => 93 ) [1] => Array ( [nicename] => United States [phonecode] => 1 )";
I want the following string:
Array ( [0] => Array ( [nicename] => "Afghanistan" [phonecode] => 93 ) [1] => Array ( [nicename] => "United States" [phonecode] => 1 )
How can I do that?
Note: This String shows only two countries, but the actual data will have more than a hundred counties.
I was thinking of doing something like
$string = preg_replace("/[[:alpha:]]/", "/\"[[:alpha:]]\"/", $string);
But the problem is that for the second argument, (1) how would PHP know what that character class [[:alpha:]] is and (2) The names of countries might contain spaces in addition to alphabetical characters.
You should really be doing this where the array is built but it can be done with a regex...
You need to capture everything after nicename until a [ or ) (e.g. if the nicename is at the end or middle of the "array").
Using something like:
(\[nicename\] => )([^\[)]+)
should accomplish that, then you need to quote the found country name:
$1"$2"
Demo: https://regex101.com/r/7TeUQu/1
this has extra spaces after the country name since whitespace were allowed there. In PHP we'll need to use preg_replace_callback and the trim function to resolve this.
$regex = '/(\[nicename\] => )([^\[)]+)/';
$replace = '$1"$2" ';
$string = 'Array ( [0] => Array ( [nicename] => Afghanistan [phonecode] => 93 ) [1] => Array ( [nicename] => United States [phonecode] => 1 )';
$string = preg_replace_callback($regex, function($match) {
return $match[1] . '"' . trim($match[2]) . '" ';
}, $string);
echo $string;
PHP Demo: https://eval.in/699678
Here you go:
$string = preg_replace('/(\[nicename\] =>) ([a-zA-Z ]+) \[/', '$1 "$2" [', $string);

Add <br /> after 3rd symbol in Array

I have the following variable:
$checkbox = implode(';', $_POST['product']);
$checkbox is equal to "Product Name;Price;Unit", how can I add a break after every line?
At the moment $checkbox is equal to:
ASFP4040;18.95;1;ASFP4048;21;1;ASGS100100;25.45;1
I need it to be like:
ASFP4040;18.95;1;
ASFP4048;21;1;
ASGS100100;25.45;1;
EDIT:
I am writing this to a .TXT file, \n shows as text and doesn't actually create a new line.
As I'm not sure, how your $_POST['products'] var looks like, you might like one of these options:
If you have everything in a single array element like this
Array
(
[0] => ASFP4040
[1] => 18.95
[2] => 1
[3] => ASFP4048
[4] => 21
[5] => 1
[6] => ASGS100100
[7] => 25.45
[8] => 1
)
you could split the array into chunks and join them together
$data = implode("\n", array_map(function($chunk) {
return implode(';', $chunk);
}, array_chunk($_POST['product'], 3)));
Alternatively, if you have an array of strings like below:
Array
(
[0] => ASFP4040;18.95;1
[1] => ASFP4048;21;1
[2] => ASGS100100;25.45;1
)
a simple implode would be enough
$data = implode("\n", $_POST['product']);
Try this:
echo "'".implode("','",$checkbox)."'<br>";
You can use regular expressions to do this. Just replace my $str with your $checkbox.
$str = 'ASFP4040;18.95;1;ASFP4048;21;1;ASGS100100;25.45;1';
$str2 = preg_replace('/((?:(?:[^;]+);){3})/',"$1\n",$str);
echo $str2;
As explained in Magnus Eriksson's comment and mine, you just have to use "\n" as first parameter of your implode:
$checkbox = implode("\n", $_POST['product']);
Please notice the use of double quotes (") in order for \n to be used as a linebreak.

How to get the strings out of this?

I am trying to get some specific values out of the following string:
{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"
I want to get 'Toyota' out of that. The string is randomly generated, so it could be Benz or Pontiac.
Not really sure what this crazy string is from, but if you've accurately shown the format, this will extract the strings you're after:
$string = '{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"';
$string = array_filter(
explode(',',
preg_replace(
array('/"/', '/{/', '/:/', '"car"'),
array('', ',', '', ''),
$string
)
)
);
print_r($string);
// Output: Array ( [1] => Toyota [2] => honda [3] => BMW [4] => Hyundai )
... if, instead, this is just a horrible typeo and this is supposed to be JSON, use json_decode:
$string = '[{"car":"Toyota"},{"car":"honda"},{"car":"BMW"},{"car":"Hyundai"}]'; // <-- valid JSON
$data = json_decode($string, true);
print_r($data);
// Output: Array ( [0] => Array ( [car] => Toyota ) [1] => Array ( [car] => honda ) [2] => Array ( [car] => BMW ) [3] => Array ( [car] => Hyundai ) )
Documentation
preg_replace - http://php.net/manual/en/function.preg-replace.php
array_filter - http://php.net/manual/en/function.array-filter.php
explode - http://php.net/manual/en/function.explode.php
json_decode - http://php.net/manual/en/function.json-decode.php
Although this looks like a corrupt piece of JSON, I would say you can get the first car with explode().
$string = '{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"';
$string = explode("{", $string);
$firstcar = $string[1]; //your string starts with {, so $string[0] would be empty
$firstcar = explode(":", $firstcar);
$caryouarelookingfor = $firstcar[1]; // [0] would be 'car', [1] will be 'Toyota'
echo $caryouarelookingfor // output: "Toyota"
But, as also mentioned in the comments, the string looks like a corrupt piece of JSON, so perhaps you want to fix the construction of this string. :)
EDIT: typo in code, as said in first comment.

php explode something into array, but using values in between

I have a string I want to clean up and put into an array so that I can search through it in mysql.
// Here's one example of what the string might have:
$string1 = "(1) *value1* *value2*; (2) *value3* *value4* *value5*; (3) *value6*";
// And here's another possibility:
$string2 = "*value1* *value2* *value3* *value4*";
// I want to remove all the "(#)" stuff, and explode all the values into an array
// This is what I have so far:
// $string can be like the examples $string1 or $string2
$string_clean = str_replace("* *","",trim(preg_replace("/\((\d)\)/i", "", $string)));
$my_array = explode('*', trim($string_clean, '*'));
However, this is what I'm getting:
Array ( [0] => value1 [1] => [2] => value2 [3] => [4] => value3 [5] => [6] => value4 [7] => [8] => value5 )
I suppose I could just find a function to remove all empty items from the array, but I'm wondering if there's a more effective way to do this?
You need preg_match_all():
preg_match_all('#\*([^*]+)\*#', $string, $matches);
$result = $matches[1];
// $result is array('value1', 'value2', ...)
This will find all *something* and return the strings between the *.

How can I convert a sentence to an array of words?

From this string:
$input = "Some terms with spaces between";
how can I produce this array?
$output = ['Some', 'terms', 'with', 'spaces', 'between'];
You could use explode, split or preg_split.
explode uses a fixed string:
$parts = explode(' ', $string);
while split and preg_split use a regular expression:
$parts = split(' +', $string);
$parts = preg_split('/ +/', $string);
An example where the regular expression based splitting is useful:
$string = 'foo bar'; // multiple spaces
var_dump(explode(' ', $string));
var_dump(split(' +', $string));
var_dump(preg_split('/ +/', $string));
$parts = explode(" ", $str);
print_r(str_word_count("this is a sentence", 1));
Results in:
Array ( [0] => this [1] => is [2] => a [3] => sentence )
Just thought that it'd be worth mentioning that the regular expression Gumbo posted—although it will more than likely suffice for most—may not catch all cases of white-space. An example: Using the regular expression in the approved answer on the string below:
$sentence = "Hello my name is peter string splitter";
Provided me with the following output through print_r:
Array
(
[0] => Hello
[1] => my
[2] => name
[3] => is
[4] => peter
[5] => string
[6] => splitter
)
Where as, when using the following regular expression:
preg_split('/\s+/', $sentence);
Provided me with the following (desired) output:
Array
(
[0] => Hello
[1] => my
[2] => name
[3] => is
[4] => peter
[5] => string
[6] => splitter
)
Hope it helps anyone stuck at a similar hurdle and is confused as to why.
Just a question, but are you trying to make json out of the data? If so, then you might consider something like this:
return json_encode(explode(' ', $inputString));

Categories