PHP Match String Pattern and Get Variable - php

I looked up some reference like this question and this question but could not figure out what I need to do.
What I am trying to do is:
Say, I have two strings:
$str1 = "link/usa";
$str2 = "link/{country}";
Now I want to check if this the pattern matches. If they match, I want the value of country to be set usa.
$country = "usa";
I also want it to work in cases like:
$str1 = "link/usa/texas";
$str2 = "link/{country}/{place}";
Maybe integers as well. Like match every braces and provide the variable with value. (And, yes better performance if possible)
I cannot get a work around since I am very new to regular expresssions. Thanks in advance.

It will give you results as expected
$str1 = "link/usa";
$str2 = "link/{country}";
if(preg_match('~link/([a-z]+)~i', $str1, $matches1) && preg_match('~link/{([a-z]+)}~i', $str2, $matches2)){
$$matches2[1] = $matches1[1];
echo $country;
}
Note: Above code will just parse alphabets, you can extend characters in range as per need.
UPDATE:
You can also do it using explode, see example below:
$val1 = explode('/', $str1);
$val2 = explode('/', $str2);
${rtrim(ltrim($val2[1],'{'), '}')} = $val1[1];
echo $country;
UPDATE 2
$str1 = "link/usa/texas/2/";
$str2 = "/link/{country}/{city}/{page}";
if(preg_match_all('~/([a-z0-9]+)~i', $str1, $matches1) && preg_match_all('~{([a-z]+)}~i', $str2, $matches2)){
foreach($matches2[1] as $key => $matches){
$$matches = $matches1[1][$key];
}
echo $country;
echo '<br>';
echo $city;
echo '<br>';
echo $page;
}

I don't see the point to use the key as variable name when you can built an associative array that will be probably more handy to use later and that avoids to write ugly dynamic variable names ${the_name_of_the_var_${of_my_var_${of_your_var}}}:
$str1 = "link/usa/texas";
$str2 = "link/{country}/{place}";
function combine($pattern, $values) {
$keys = array_map(function ($i) { return trim($i, '{}'); },
explode('/', $pattern));
$values = explode('/', $values);
if (array_shift($keys) == array_shift($values) && count($keys) &&
count($keys) == count($values))
return array_combine($keys, $values);
else throw new Exception ("invalid format");
}
print_r(combine($str2, $str1));

Related

how to compare multiple id avaialble in antoher string?

below are two string variable.
how to check $str2 is contain all values of $str1?
$str1 = ',2,4,13,11,';
$str2 = ',1,2,22,20,6,4,21,18,4.146,11,1.124,13,';
i know its possible using loop, but i want to know that is it possible directly or not?
With array_diff and explode functions:
$str1 = ',2,4,13,11,';
$str2 = ',1,2,22,20,6,4,21,18,4.146,11,1.124,13,';
$contains_all = ! array_diff(explode(',', trim($str1,',')), explode(',', trim($str2,',')));
var_dump($contains_all); // true
Something like this?
<?php
$str1 = ',2,4,13,11';
$str2 = ',1,2,22,20,6,4,21,18,4.146,11,1.124,13,';
$arr1 = explode(",",$str1);
$arr2 = explode(",",$str2);
$subArray = count(array_intersect($arr1 , $arr2)) == count($arr1);
if($subArray) {
echo 'TRUE';
} else {
echo 'FALSE';
}
?>

Retrieve word from string

I have this code:
$getClass = $params->get('pageclass_sfx');
var_dump($getClass); die();
The code above returns this:
string(24) "sl-articulo sl-categoria"
How can I retrieve the specific word I want without mattering its position?
Ive seen people use arrays for this but that would depend on the position (I think) that you enter these strings and these positions may vary.
For example:
$myvalue = $params->get('pageclass_sfx');
$arr = explode(' ',trim($myvalue));
echo $arr[0];
$arr[0] would return: sl-articulo
$arr[1] would return: sl-categoria
Thanks.
You can use substr for that in combination with strpos:
http://nl1.php.net/substr
http://nl1.php.net/strpos
$word = 'sl-categoria';
$page_class_sfx = $params->get('page_class_sfx');
if (false !== ($pos = strpos($page_class_sfx, $word))) {
// stupid because you already have the word... But this is what you request if I understand correctly
echo 'found: ' . substr($page_class_sfx, $pos, strlen($word));
}
Not sure if you want to get a word from the string if you already know the word... You want to know if it's there? false !== strpos($page_class_sfx, $word) would be enough.
If you know exactly what strings you're looking for, then stripos() should be sufficient (or strpos() if you need case-sensitivity). For example:
$myvalue = $params->get('pageclass_sfx');
$pos = stripos($myvalue, "sl-articulo");
if ($pos === FALSE) {
// string "sl-articulo" was not found
} else {
// string "sl-articulo" was found at character position $pos
}
If you need to check if some word are in string you may use preg_match function.
if (preg_match('/some-word/', 'many some-words')) {
echo 'some-word';
}
But this solution can be used for a small list of needed words.
For other cases i suggest you to use some of this.
$myvalue = $params->get('pageclass_sfx');
$arr = explode(' ',trim($myvalue));
$result = array();
foreach($arr as $key=> $value) {
// This will calculates all data in string.
if (!isset($result[$value])) {
$result[$value] = array(); // or 0 if you don`t need to use positions
}
$result[$value][] = $key; // For all positions
// $result[$value] ++; // For count of this word in string
}
// You can just test some words like follow:
if (isset($result['sl-categoria'])) {
var_dump($result['sl-categoria']);
}

match two strings and compare each letter in php

I googled this question I can't to find the exact solution...
I have 2 variables...
$s1 = "ABC"; //or "BC"
$s2 = "BC"; //or "Bangalore"
I have to compare $s1 and $s2 and give the output as letters which is not present in $s2
eg : "A" // or"C"
Like that
I have to compare $s2 and $s1 and give the output as letters which is not present in $s1
eg : null // or"angalore"
What I tried..
I spit the strings to array...
Using nested for loop to find the non matched letters...
I wrote code more than 35 lines..
But no result :(
Please help me ......
echo str_ireplace(str_split($s2), "", $s1); // output: A
You can use array_diff() here:
function str_compare($str1, $str2)
{
$str1chars = str_split($str1);
$str2chars = str_split($str2);
$diff = array_diff($str1chars, $str2chars)
return implode($diff);
}
By calling the function as follows:
$diffchars = str_compare('ABC', 'BC');
You will receive a string containing the characters that do not appear in both strings. In this example, it'll be A, because that character appears in $str1, but not in $str2.
You can use str_split and array_diff like :
<?php
$s1 = 'abcedf';
$s2 = 'xzcedf5460gf';
print_r(array_diff(str_split($s1), str_split($s2)));
Use array_diff():
function str_diff($str1, $str2) {
$arr1 = str_split($str1);
$arr2 = str_split($str2);
$diff = array_diff($arr1, $arr2);
return implode($diff);
}
Usage:
echo str_diff('BC', 'Bangalore'); // => C
echo str_diff('ABC', 'BC'); // => A
Ok to do this
$str1s = "abc";
$str2s = "BCd";
function findNot($str1, $str2, $asArray = false){
$returnValue = array_diff(array_unique(str_split(strtolower($str1))), array_unique(str_split(strtolower($str2))));
if($asArray == false){
return implode($returnValue);
}else{
return $returnValue;
}
}
echo findNot($str1s, $str2s); //gives a string
echo findNot($str1s, $str2s, true); //gives array of characters
This allows you to return as either array or string.

php call array from string

I have a string that contains elements from array.
$str = '[some][string]';
$array = array();
How can I get the value of $array['some']['string'] using $str?
This will work for any number of keys:
$keys = explode('][', substr($str, 1, -1));
$value = $array;
foreach($keys as $key)
$value = $value[$key];
echo $value
You can do so by using eval, don't know if your comfortable with it:
$array['some']['string'] = 'test';
$str = '[some][string]';
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));
$value = eval($code);
echo $value; # test
However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.
Another example if you need to write access to the array item, you can do the following:
$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
$value = &$value[$segment];
}
echo $value;
$value = 'changed';
print_r($array);
This is actually the same principle as in Eric's answer but referencing the variable.
// trim the start and end brackets
$str = trim($str, '[]');
// explode the keys into an array
$keys = explode('][', $str);
// reference the array using the stored keys
$value = $array[$keys[0][$keys[1]];
I think regexp should do the trick better:
$array['some']['string'] = 'test';
$str = '[some][string]';
if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
{
if (isset($array[$keys['key1']][$keys['key2']]))
echo $array[$keys['key1']][$keys['key2']]; // do what you need
}
But I would think twice before dealing with arrays your way :D

built in function to combine overlapping string sequences in php?

Is there a built in function in PHP that would combine 2 strings into 1?
Example:
$string1 = 'abcde';
$string2 = 'cdefg';
Combine to get: abcdefg.
If the exact overlapping sequence and the position are known, then it is possible to write a code to merge them.
TIA
I found the substr_replace method to return funny results.
Especially when working with url strings. I just wrote this function.
It seems to be working perfectly for my needs.
The function will return the longest possible match by default.
function findOverlap($str1, $str2){
$return = array();
$sl1 = strlen($str1);
$sl2 = strlen($str2);
$max = $sl1>$sl2?$sl2:$sl1;
$i=1;
while($i<=$max){
$s1 = substr($str1, -$i);
$s2 = substr($str2, 0, $i);
if($s1 == $s2){
$return[] = $s1;
}
$i++;
}
if(!empty($return)){
return $return;
}
return false;
}
function replaceOverlap($str1, $str2, $length = "long"){
if($overlap = findOverlap($str1, $str2)){
switch($length){
case "short":
$overlap = $overlap[0];
break;
case "long":
default:
$overlap = $overlap[count($overlap)-1];
break;
}
$str1 = substr($str1, 0, -strlen($overlap));
$str2 = substr($str2, strlen($overlap));
return $str1.$overlap.$str2;
}
return false;
}
Usage to get the maximum length match:
echo replaceOverlap("abxcdex", "xcdexfg"); //Result: abxcdexfg
To get the first match instead of the last match call the function like this:
echo replaceOverlap("abxcdex", "xcdexfg", “short”); //Result: abxcdexcdexfg
To get the overlapping string just call:
echo findOverlap("abxcdex", "xcdexfg"); //Result: array( 0 => "x", 1 => "xcdex" )
It's possible using substr_replace() and strcspn():
$string1 = 'abcde';
$string2 = 'cdefgh';
echo substr_replace($string1, $string2, strcspn($string1, $string2)); // abcdefgh
No, there is no builtin function, but you can easily write one yourself by using substr and a loop to see how much of the strings that overlap.

Categories