I have a PHP variable called $array, which will output something like
"...", "...", "...", "...", ... when echo'd
but ... may content some character like " , , and spaces or may even contain ", "
How can I change it to an array like Array([0] => ... [1] => ... [2] => ... [3] => ... etc)?
PHP explode
$array = explode(",",$array); // split the string into an array([0] => '"..."', etc)
foreach ($array as $entry) {
// clean up the strings as needed
}
You can use the str_replace function :
$str = "....'...,,,";
$unwantedChars = array("'", ",");
$cleanString = str_replace($unwantedChars, "",$str);
echo $cleanString;
You can add as many characters in the unwantedChar array you want
Related
Like the title says I am getting the API response just fine. I've cleaned the response data up several different ways. When attempting to use explode, I cannot get it to assign the string as the key and value pairs needed. I'll post some of the data below. If I need to delimit the data differently for ease, I will. Tried dozens of examples over the last fourteen hours. Please help!
# Find the part of the string after the description
$mysearchstring = 'color';
# Minus one keeps the quote mark in front of color
$position = (stripos($response, $mysearchstring)-1);
#This selects the text after the description to the end of the file
$after_descrip = substr($response, $position);
echo "</br>__________Show the data after the description________________</br>";
echo $after_descrip;
echo "</br>__________Show the cleaned data________________</br>";
$cleaned = $after_descrip;
$cleaned1 = str_replace('{', "", $cleaned);
$cleaned2 = str_replace('}', "", $cleaned1);
$cleaned3 = str_replace('[', "", $cleaned2);
$cleaned4 = str_replace(']', "", $cleaned3);
$cleaned5 = str_replace('https://', "", $cleaned4);
$cleaned6 = str_replace('"', "", $cleaned5);
echo $cleaned6;
echo "</br>__________Explode is next________________</br>";
#Turn the string into an array but not the array I want
$last_half = explode(':', $cleaned6);
print_r($last_half);
}
The cleaned data looks like this:
color:#3C3C3D,iconType:vector,iconUrl:cdn.coinranking.com/rk4RKHOuW/eth.svg,websiteUrl:www.ethereum.org,socials:name:ethereum,url:twitter.com/ethereum,type:twitter,name:ethereum,url:www.reddit.com/r/ethereum/
The resulting array looks like this:
Array ( [0] => color [1] => #3C3C3D,iconType [2] => vector,iconUrl [3] => cdn.coinranking.com/rk4RKHOuW/eth.svg,websiteUrl [4] => www.ethereum.org,socials [5] => name [6] => ethereum,url [7] => twitter.com/ethereum,type [8] => twitter,name [9] => ethereum,url [10] => www.reddit.com/r/ethereum/,type [11] => reddit,name [12] => ethtrader,url [13] =>
Color should be the first key, #3C3C3D should be the first value. The rest of the data should follow that format.
What do you think is the best way to go? Thank you.
-Rusty
You should use json_decode function. https://www.php.net/manual/en/function.json-decode.php
This function can decode json to array and object
Just one more step...
$last_half = explode(',', $cleaned6);
foreach($last_half as $item){
list($k, $v) = explode(':', $item);
$result[$k] = $v;
}
print_r($result);
So you want an array where "color" -> "#3C3C3D" ?
Thats the way:
$last_half = explode(',', $last_half);
$new_array = [];
foreach ($last_half as $item) {
[$key, $value] = explode(':', $item, 2);
$new_array[$key] = $value;
}
Now new array should be like you want :)
But wait, just noticed that initially you have json, so you should always go with native functions and use that to parse this string. (as the other answer says)
Best,
intxcc
I have a PHP array that looks like this..
Array
(
[0] => post: 746
[1] => post: 2
[2] => post: 84
)
I am trying to remove the post: from each item in the array and return one that looks like this...
Array
(
[0] => 746
[1] => 2
[2] => 84
)
I have attempted to use preg_replace like this...
$array = preg_replace('/^post: *([0-9]+)/', $array );
print_r($array);
But this is not working for me, how should I be doing this?
You've missed the second argument of preg_replace function, which is with what should replace the match, also your regex has small problem, here is the fixed version:
preg_replace('/^post:\s*([0-9]+)$/', '$1', $array );
Demo: https://3v4l.org/64fO6
You don't have a pattern for the replacement, or a empty string place holder.
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject)
Is what you are trying to do (there are other args, but they are optional).
$array = preg_replace('/post: /', '', $array );
Should do it.
<?php
$array=array("post: 746",
"post: 2",
"post: 84");
$array = preg_replace('/^post: /', '', $array );
print_r($array);
?>
Array
(
[0] => 746
[1] => 2
[2] => 84
)
You could do this without using a regex using array_map and substr to check the prefix and return the string without the prefix:
$items = [
"post: 674",
"post: 2",
"post: 84",
];
$result = array_map(function($x){
$prefix = "post: ";
if (substr($x, 0, strlen($prefix)) == $prefix) {
return substr($x, strlen($prefix));
}
return $x;
}, $items);
print_r($result);
Result:
Array
(
[0] => 674
[1] => 2
[2] => 84
)
There are many ways to do this that don't involve regular expressions, which are really not needed for breaking up a simple string like this.
For example:
<?php
$input = Array( 'post: 746', 'post: 2', 'post: 84');
$output = array_map(function ($n) {
$o = explode(': ', $n);
return (int)$o[1];
}, $input);
var_dump($output);
And here's another one that is probably even faster:
<?php
$input = Array( 'post: 746', 'post: 2', 'post: 84');
$output = array_map(function ($n) {
return (int)substr($n, strpos($n, ':')+1);
}, $input);
var_dump($output);
If you don't need integers in the output just remove the cast to int.
Or just use str_replace, which in many cases like this is a drop in replacement for preg_replace.
<?php
$input = Array( 'post: 746', 'post: 2', 'post: 84');
$output = str_replace('post: ', '', $input);
var_dump($output);
You can use array_map() to iterate the array then strip out any non-digital characters via filter_var() with FILTER_SANITIZE_NUMBER_INT or trim() with a "character mask" containing the six undesired characters.
You can also let preg_replace() do the iterating for you. Using preg_replace() offers the most brief syntax, but regular expressions are often slower than non-preg_ techniques and it may be overkill for your seemingly simple task.
Codes: (Demo)
$array = ["post: 746", "post: 2", "post: 84"];
// remove all non-integer characters
var_export(array_map(function($v){return filter_var($v, FILTER_SANITIZE_NUMBER_INT);}, $array));
// only necessary if you have elements with non-"post: " AND non-integer substrings
var_export(preg_replace('~^post: ~', '', $array));
// I shuffled the character mask to prove order doesn't matter
var_export(array_map(function($v){return trim($v, ': opst');}, $array));
Output: (from each technique is the same)
array (
0 => '746',
1 => '2',
2 => '84',
)
p.s. If anyone is going to entertain the idea of using explode() to create an array of each element then store the second element of the array as the new desired string (and I wouldn't go to such trouble) be sure to:
split on or : (colon, space) or even post: (post, colon, space) because splitting on : (colon only) forces you to tidy up the second element's leading space and
use explode()'s 3rd parameter (limit) and set it to 2 because logically, you don't need more than two elements
Hello I have this variable
$str="101,102,103,104,105,#,106#107"
//or array
$str_arr = array( 0 => '101', 1 => '102', 2 => '103', 3 => '104',
4 => '105', 8 => '#' , 9 => '106# 107');
I want to remove the symbol # between comma
The symbol may be /,\,-,| not comma
The symbol between number is correct, so it remains (key 9)
I do not know, if I had these cases but I will study it
$str="101,102,103,104,105#, 106" // One of the symbols in the end of number
$str="101,102,103,104,105,#106" // One of the symbols in the the beginning of number
This is The different possibilities
$str="101,102,103,/,104|,#105,106#107" //replace all symbol in the beginning and the end of number not betwwen number
this is result
$str="101,102,103,104,105,106#107";
Thanks
Convert the string to array using explode by ,. Parse the array using foreach loop. trim() the # or any set of characters like #-|\/ from the beginning and end of every string, then check for empty values and push non empty values to the $arr array. Then you can join the array into a string using implode. You can do it like this:
$arr = array();
$str="101,102,103,104,105,#,106#107";
$str = explode(',', $str);
foreach($str as $s){
$s = trim($s, "#-|\/");
if(!empty($s)){
$arr[] = $s;
}
}
$final_str = implode(',', $arr);
var_dump($final_str);
In php when user saves a text, I need to split string as
"genesis1:3-16" ==> "genesis", "1", "3", "16"
"revelation2:3-5" ==> "revelation", "2", "3", "5"
The conditions are there will be no white spaces between all characters I need to split according to symbol ":", "-", and character. the numbers can go up to only '999' 3 digits.
$sample = "genesis1:3-16";
//magic happens....
$book = ""; // genesis
$chapter = ""; // 1
$start_verse = ""; // 3
$end_verse = ""; //16
I have limited knowledge of reg expression and can't figure out using only strpos and substr...
Thank you in advance
I think this regex would accomplish what you are after:
([a-z]+)(\d{1,3}):(\d{1,3})-(\d{1,3})
Demo (with explanation of what each part does): https://regex101.com/r/uP4gW6/1
PHP Usage:
preg_match('~([a-z]+)(\d{1,3}):(\d{1,3})-(\d{1,3})~', 'genesis1:3-16', $data);
print_r($data);
Output:
Array
(
[0] => genesis1:3-16
[1] => genesis
[2] => 1
[3] => 3
[4] => 16
)
With preg_match the 0 index is the found content. The subsequent indexes are each captured group.
If you have a fixed set of names the book could be you could replace [a-z]+ with that list seperated by |, for example revelation|genesis|othername.
$parts = array();
preg_match('/^(.*?)\s*(\d+):(\d+)-(\d+)$/', $sample, $parts);
$book = $parts[1];
$chapter = $parts[2];
$startVerse = $parts[3];
$endVerse = $parts[4];
you could use this simple pattern
([a-zA-Z]+|\d{1,3})
Demo
I have a problem, I want to split a string variable using the explode function but there are a limitation, imagine having the next string variable with the next value :
$data = "3, 18, 'My name is john, i like to play piano'";
Using the explode function : explode(",", $data), the output will be :
array(
[0] => 3,
[1] => 18,
[2] => 'My name is john,
[3] => i like to play piano'
);
My target is to split the variable $data by comma excluding the ones that are between ' ' chatacters.
e.g. array(
[0] => 3,
[1] => 18,
[2] => 'My name is john, i like to play piano'
);
If anyone can tell me a way to do this, I'd be grateful.
This looks rather like CSV data. You can use str_getcsv to parse this.
var_dump(str_getcsv("3, 18, 'My name is john, i like to play piano'", ',', "'"));
should result in:
array(3) {
[0] =>
string(1) "3"
[1] =>
string(3) " 18"
[2] =>
string(12) "My name is john, i like to play piano"
}
You may want to apply trim to each of the array elements too, by using array_map:
$string = "3, 18, 'My name is john, i like to play piano'";
var_dump(array_map('trim', str_getcsv($string, ',', "'")));
Use: str_getcsv
// set the delimiter with ',', and set enclosure with single quote
$arr = str_getcsv ($data, ',', "'");
You can use the str_getcsv() function as:
$data = "3, 18, 'My name is john, i like to play piano'";
$pieces = str_getcsv($data, ',', "'");
The first argument to the function is the string to be split.
The second argument is the delimiter on which you need to split.
And the third argument is the single character that when used as a pair (unsescaped) inside the first argument, will be treated as one field, effectively ignoring the delimiters between this pair.