PHP Divide variable into two different variables - php

I have this variable : $lang['_city']
I need to divide it in two portions.
One portion will be $key == lang and second portion will be $ind == _city
I think I can do it with some sort of regexp but I am not good with it.
Can you help me?
P.S. The above example is only a sample. I need an abstract function that will do it with any passed variable.. So for example, get whatever is before [ and cut the $, and then get whatever is inside [' '].. I know the logic but not the way to do it :)
Also the new values will have to be assigned each one to a variable as explained before.
Thanks

$string = "\$foo['bar']";
preg_match('~^\$(?\'key\'[^\[]+)\[\'(?\'ind\'[^\']+)~', $string, $matches);
var_dump($matches['key'], $matches['ind']);
http://ideone.com/XaopX

Regexp for preg_match would be: ~^\$([^\[]+)\[\s*("[^"]+"|'[^']+')\s*\]$~ (you'll need to escape ' or " when moving to string).
Than:
$key = $match[1];
$ind = substr( $match[2], 1, -1);

You do not even need regexp here :)
$str = "\$lang['city']";
$tmp = explode('[', $str);
$key = ltrim($tmp[0], '$');
$ind = trim($tmp[1], ']\'"');
echo $key . '=>' . $ind;
Starting from PHP 5.4 you could do it even shorter
$str = "\$lang['city']";
$key = ltrim(explode('[', $str)[0], '$');
$ind = trim(explode('[', $str)[1], ']\'"');
echo $key . '=>' . $ind;

Related

PHP regular expression

I have an array
$array = ['download.png', 'download-1.png', 'download-2.png']
I want a regular expression that can match all three elements. So far I've tried and gotten something like
/('."$filename".')\-*[0-9]*$/
where $filename = 'download.png'
If it helps I am trying to use the regex in this
foreach($len as $value){
if(preg_match('/('."$filename".')\-*[0-9]*$/', $value->getValue()) ){
$array[] = $value->getValue();
var_dump( $array); echo '<br>';
}
}
help me anyone thanks in advance!
Try "/" . explode($filename, '.')[0] . "(?:-\d)?\.png/"
explode($filename, '.')[0] splits $filename into ['download', 'png'] and then gets the first element in that array, download.
(?:-\d)? is an optional (it's the ? that makes it optional) non-capturing group (that's the (?:) that matches a dash and then a number. This means that it's optional to match the -1.
From what I understand from your question, $value->getValue() is something like download-2.png. Your regex isn't matching the .png extension. I've added \.png to my regex for this.
An alternative solution without regex.
Explode on "-" if there is two items in the array it has "-" included in name.
$array = ['download.png', 'download-1.png', 'download-2.png'];
Foreach($array as $val){
$exp = explode("-", $val);
If(isset($exp[1])){
Echo "name is: " . $exp[0] . "-" . $exp[1] . "\n";
}Else{
Echo "name is: " . $exp[0] ."\n";
}
}
https://3v4l.org/5ElW3

Remove quotes from string inside of array

I have a string that looks like this:
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
I need to get rid of the " that are inside of the [] array so it looks like this:
$string = '"excludeIF":[miniTrack, tubeTrack, boxTrack]';
I was trying some regex but I kept getting rid of all of the quotes.
For this particular example:
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
preg_match("/((?<=\[).*(?=\]))/", $string, $match);
$change = str_replace('"', "", $match[0]);
$result = preg_replace("/$match[0]/", $change, $string);
What this does is it gets the content inside the square brackets, removes the quotes, then replaces the original content with the cleaned content.
This may run into errors if you have the exact same string outside of square brackets later on, but it should be an easy fix if you understand what I've written.
Hope it helps.
PS. It would also help if you showed us what regexes you were trying, as you were, perhaps, on the right path but just had some misunderstandings.
So yeah I agree with the comment about the XY Problem, but I would still like to try help.
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
You will now need to find the start and end positions of the string that you want edited. This can be done by the following:
$stringPosition1 = strpos($string,'[');
$stringPosition2 = strpos($string,']');
Now you have the correct positions you are able to do a substr() to find the exact string you want edited.
$str = substr($string,$stringPosition1,$stringPosition2);
From here you can do a simple str_replace()
$replacedString = str_replace('"','',$str);
$result = '"excludeIF":' . $replacedString;
It is an excellent idea to look at the PHP docs if you struggle to understand any of the above functions. I truly believe that you are only as good at coding as your knowledge of the language is. So please have a read of the following documents:
Str_pos: http://php.net/manual/en/function.strpos.php
Sub_str: http://php.net/manual/en/function.substr.php
Str_replace: http://php.net/manual/en/function.str-replace.php
test this code:
<?php
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
$str_array = str_split($string);
$string_new = '';
$id = 0;
foreach ($str_array as $value) {
if($value == '[' || $id != 0){
$id = ($value != ']') ? 1 : 0;
$string_new .= ($value != "\"") ? $value : '' ;
} else {
$string_new .= $value;
}
}
echo $string_new;
//RESULT "excludeIF":[miniTrack,isTriangleHanger,tubeTrack,boxTrack]
?>
Good luck!
EDIT
<?php
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
$part = str_replace("\"","",(strstr($string,'[')));
$string = substr($string,0,strpos($string,'[')).$part;
echo $string;
?>
Other possible solution.
Fun with code!

How to split and count the words with single quotes (')?

I want to split word like who's and count it into 2 words:
who = 1
s = 1
I think it will use preg_split to do this job, but I don't understand how to do it.
You may use explode() to get it.
$word= "who's'who";
$results= array();
$parts = explode ("'", $word);
foreach ($parts as $part) $results[$part]++;
You then may output like:
foreach ($results as $word => $count) echo $word . " = " . $count. "<br>";
The output should be:
who = 2
s = 1
You could use preg_split:
$str = "who's";
$words = preg_split("/\'/", $str);
But, as others have mentioned, explode is far easier, and will have better performance

matching url to another url

I am faced with rather unusual situation
I will have url in any of the 3 formats:
http://example.com/?p=12
http://example.com/a-b/
http://example.com/a.html
Now, I need to match with a url like
http://example.com/?p=12&t=1
http://example.com/a-b/?t=1
http://example.com/a.html?t=1
How can I achieve this? Please help
I know I can use like:
stristr('http://example.com/?p=12','http://example.com/?p=12&t=1')
but this will also match when
http://example.com/?p=123 (as it matches p=12)
Help guys, please.
A simple way to accomplish this would be to use PHP's parse_url() and parse_str().
http://www.php.net/manual/en/function.parse-url.php
http://www.php.net/manual/en/function.parse-str.php
Take your urls and run them through parse_url(), and take the resulting $result['query']. Run these through parse_str() and you'll end up with two associative arrays of the variable names and their values.
Basically, you'll want to return true if the $result['path']s match, and if any keys which are in both $result['query'] contain the same values.
code example:
function urlMatch($url1, $url2)
{
// parse the urls
$r1 = parse_url($url1);
$r2 = parse_url($url2);
// get the variables out of the queries
parse_str($r1['query'], $v1);
parse_str($r2['query'], $v2);
// match the domains and paths
if ($r1['host'] != $r2['host'] || $r1['path'] != $r2['path'])
return false;
// match the arrays
foreach ($v1 as $key => $value)
if (array_key_exists($key, $v2) && $value != $v2[$key])
return false;
// if we haven't returned already, then the queries match
return true;
}
A very quick (and somewhat dirty) way to achieve this is via the following regex:
$regex = '#^' . preg_quote($url, '#') . '[?&$]#';
Where $url is the URL you need to search for. In the above, we look for the URL in the beginning of whatever the regex is matched upon, followed by either a ?, a & or the end-of-line anchor. This is not bullet-proof but may be sufficient (#Mala already posted the "right" approach).
Below, I've posted an example of use (and the result):
$urls = array(
'http://example.com/?p=12',
'http://example.com/a-b/',
'http://example.com/a.html'
);
$tests = array(
'http://example.com/?p=12&t=1',
'http://example.com/a-b/?t=1',
'http://example.com/a.html?t=1',
'http://example.com/?p=123'
);
foreach ($urls as $url) {
$regex = '#^' . preg_quote($url, '#') . '[?&$]#';
print $url . ' - ' . $regex . "\n";
foreach ($tests as $test) {
$match = preg_match($regex, $test);
print ' ' . ($match ? '+' : '-') . ' ' . $test . "\n";
}
}
Result:
http://example.com/?p=12 - #^http\://example\.com/\?p\=12[?&$]#
+ http://example.com/?p=12&t=1
- http://example.com/a-b/?t=1
- http://example.com/a.html?t=1
- http://example.com/?p=123
http://example.com/a-b/ - #^http\://example\.com/a-b/[?&$]#
- http://example.com/?p=12&t=1
+ http://example.com/a-b/?t=1
- http://example.com/a.html?t=1
- http://example.com/?p=123
http://example.com/a.html - #^http\://example\.com/a\.html[?&$]#
- http://example.com/?p=12&t=1
- http://example.com/a-b/?t=1
+ http://example.com/a.html?t=1
- http://example.com/?p=123

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