get all strings within an equal reference with explode - php

I would like to get all the strings within a specific reference. example:
$string = '<abc>A1</abc><bcd>B1</bcd><abc>A2</abc><bcd>B2</bcd><abc>A3</abc>';
I would like to get all the elements inside Tags <abc>, </ abc>, listing for example A1 A2 A3.
I tried to use explode like this:
$string = '<abc>A1</abc><bcd>B1</bcd><abc>A2</abc><bcd>B2</bcd><abc>A3</abc>';
$take = explode('<abc>', $string);
foreach ($take as $value) {
$take = explode('</abc>',$value);
It returned: array array array array

You can use a regular expression
$string = '<abc>A1</abc><bcd>B1</bcd><abc>A2</abc><bcd>B2</bcd><abc>A3</abc>';
preg_match_all('/<abc>(.*?)<\/abc>/s', $string, $matches);
print_r($matches[1]);

explode function returns an array. Try this code.
$string = '<abc>A1</abc><bcd>B1</bcd><abc>A2</abc><bcd>B2</bcd><abc>A3</abc>';
$take = explode('<abc>', $string);
foreach ($take as $value) {
$take = explode('</abc>',$value);
echo "<pre>";
print_r($take);
}

Related

How to convert a certain type of string into an array with keys in php?

I have a string of this type:
string(11) "2=OK, 3=OK"
from a text file. But I would like to convert it into an array of keys this type :
array (
[2] => Ok
[3] => Ok
)
I was wondering how we could do that in PHP.
Note:- I normally use explode() and str_split() for the conversions string into array but in this case I don't know how to do it.
use explode(), foreach() along with trim()
<?php
$string = "2=OK, 3=OK" ;
$array = explode(',',$string);
$finalArray = array();
foreach($array as $arr){
$explodedString = explode('=',trim($arr));
$finalArray[$explodedString[0]] = $explodedString[1];
}
print_r($finalArray);
https://3v4l.org/ZsNY8
Explode the string by ',' symbol. You will get an array like ['2=OK', ' 3=OK']
Using foreach trim and explode each element by '=' symbol
You can use default file reading code and traverse it to achieve what you want,
$temp = [];
if ($fh = fopen('demo.txt', 'r')) {
while (!feof($fh)) {
$temp[] = fgets($fh);
}
fclose($fh);
}
array_walk($temp, function($item) use(&$r){ // & to change in address
$r = array_map('trim',explode(',', $item)); // `,` explode
array_walk($r, function(&$item1){
$item1 = explode("=",$item1); // `=` explode
});
});
$r = array_column($r,1,0);
print_r($r);
array_walk — Apply a user supplied function to every member of an array
array_map — Applies the callback to the elements of the given arrays
explode — Split a string by a string
Demo.
You can use preg_match_all along with array_combine, str_word_count
$string = "2=OK, 3=OK" ;
preg_match_all('!\d+!', $string, $matches);
$res = array_combine($matches[0], str_word_count($string, 1));
Output
echo '<pre>';
print_r($res);
Array
(
[2] => OK
[3] => OK
)
LIVE DEMO

How to extract string between two slashes php

i know that its easy to extract string between two slashes using explode() function in php, What if the string is like
localhost/used_cars/search/mk_honda/md_city/mk_toyota
i want to extract string after mk_ and till the slashes like:** honda,toyota **
any help would be highly appreciated.
I am doing like this
echo strpos(uri_string(),'mk') !== false ? $arr = explode("/", $string, 2);$first = $arr[0]; : '';
but not working because if user enter mk_honda in any position then explode() is failed to handle that.
Use regex:
http://ideone.com/DNHXsf
<?php
$input = 'localhost/used_cars/search/mk_honda/md_city/mk_toyota';
preg_match_all('#/mk_([^/]*)#', $input, $matches);
print_r($matches[1]);
?>
Output:
Array
(
[0] => honda
[1] => toyota
)
Explode your string by /, then check every element of array with strpos:
$string = 'localhost/used_cars/search/mk_honda/md_city/mk_toyota';
$parts = explode('/', $string);
$r = [];
foreach ($parts as $p) {
// use `===` as you need `mk_` in position 0
if (strpos($p, 'mk_') === 0) {
// 3 is a length of `mk_`
$r[] = substr($p, 3);
}
}
echo'<pre>',print_r($r),'</pre>';
Just try this
$str='localhost/used_cars/search/mk_honda/md_city/mk_toyota';
$str=explode('/',$str);
$final=[];
foreach ($str as $words){
(!empty(explode('_',$words)))?(isset(explode('_',$words)[1]))?$final[]=explode('_',$words)[1]:false:false;
}
$final=implode(',',$final);
echo $final;
It give output as
cars,honda,city,toyota

Convert a string to two doubles

If I have a string like this: '(1.23123, 4.123123)'
How would I convert it to two doubles?
$items = explode(',', $string);
$n1 = $items[0] // (1.23123
My attempts:
floatval($n1) // 0
(double) $n1 // 0
How can I convert?
You need to trim those parenthesis around your string . Use trim inside your explode by passing the parentheses as the charlist.
$items = explode(',', trim($str,')('));
The code
<?php
$str='(1.23123, 4.123123)';
$items = explode(',', trim($str,')('));
$items=array_map('floatval',$items);
echo $n1 = $items[0]; // "prints" 1.23123
echo $n2 = $items[1]; // "prints" 4.123123
array_map('floatval', $array) for your array
Try this code
$string = "(1.23123, 4.123123)";
preg_match_all("/[\d\.]+/", $string, $matches);
print_r($matches[0]);

explode two-item-list in array as key=>value

I'd like to explode a multi-line-string like this
color:red
material:metal
to an array like this
$array['color']=red
$array['material']=metal
any idea?
Use explode(), you can use a regexp for it, but it's simple enough without the overhead.
$data = array();
foreach (explode("\n", $dataString) as $cLine) {
list ($cKey, $cValue) = explode(':', $cLine, 2);
$data[$cKey] = $cValue;
}
As mentioned in comments, if data is coming from a Windows/DOS environment it may well have CRLF newlines, adding the following line before the foreach() would resolve that.
$dataString = str_replace("\r", "", $dataString); // remove possible \r characters
The alternative with regexp can be quite pleasant using preg_match_all() and array_combine():
$matches = array();
preg_match_all('/^(.+?):(.+)$/m', $dataString, $matches);
$data = array_combine($matches[1], $matches[2]);
Try this
$value = '1|a,2|b,3|c,4|d';
$temp = explode (',',$value);
foreach ($temp as $pair)
{
list ($k,$v) = explode ('|',$pair);
$pairs[$k] = $v;
}
print_r($pairs);
explode first on line break. Prolly \n
Then explode each of the resulting array's items on : and set a new array to that key/value.

How can I use a string to get a value from a multi dimensional array?

Say this is my string
$string = 'product[0][1][0]';
How could I use that string alone to actually get the value from an array as if I had used this:
echo $array['product'][0][1][0]
I've messed around with preg_match_all with this regex (/\[([0-9]+)\]/), but I am unable to come up with something satisfactory.
Any ideas? Thanks in advance.
You could use preg_split to get the individual array indices, then a loop to apply those indices one by one. Here's an example using a crude /[][]+/ regex to split the string up wherever it finds one or more square brackets.
(Read the [][] construct as [\]\[], i.e. a character class that matches right or left square brackets. The backslashes are optional.)
function getvalue($array, $string)
{
$indices = preg_split('/[][]+/', $string, -1, PREG_SPLIT_NO_EMPTY);
foreach ($indices as $index)
$array = $array[$index];
return $array;
}
This is prettttty hacky, but this will work. Don't know how much your array structure is going to change, either, this won't work if you get too dynamic.
$array = array();
$array['product'][0][1][0] = "lol";
$string = 'product[0][1][0]';
$firstBrace = strpos( $string, "[" );
$arrayExp = substr($string, $firstBrace );
$key = substr( $string, 0, $firstBrace );
echo $arrayExp, "<br>";
echo $key, "<br>";
$exec = "\$val = \$array['".$key."']".$arrayExp.";";
eval($exec);
echo $val;
What about using eval()?
<?php
$product[0][1][0] = "test";
eval ("\$string = \$product[0][1][0];");
echo $string . "\n";
die();
?>

Categories