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.
Related
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';
}
?>
I have two variables such as below
$string1 = array('A','b','c');
$string2 = 'bAcdadbcliek'
need to check all the characters from string1 is presents in string2 or not in php and values are dynamic.
try This
<?php
$string1 = array('A','b','c','2');
$string2 = 'bAcdadbcliek';
foreach($string1 as $newstring)
{
$finalval=strrchr($string2,$newstring);
if($finalval!="")
{
echo $newstring." ---: Available in given String<br/>";
}
else
{
echo $newstring." ---: Not Available in given String<br/>";
}
}
?>
use str_split and array_intersect
<?php
$string1 = array('A','b','c');
$string2 = 'bAcdadbcliek';
$new = str_split($string2);
$new_2 = array_intersect($string1,$new);
if(count($new_2)==count($string1))
{
echo "all matched";
}
else
{
echo "not ";
}
?>
The following function will return a boolean true/false if all values are matched. It is case-sensitive.
Basically, split $string2 into an array and intersect it, match the count of that against the count of $string1 (which is an array, not a string by the way). If the count is equal, everything was found.
$string1 = array('A','b','c');
$string2 = 'bAcdadbcliek';
function match_string(string $string, array $match_values) {
if (count(array_intersect(str_split($string), $match_values)) == count($match_values))
return true;
return false;
}
Live demo
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));
I have the following text string: "Gardening,Landscaping,Football,3D Modelling"
I need PHP to pick out the string before the phrase, "Football".
So, no matter the size of the array, the code will always scan for the phrase 'Football' and retrieve the text immediately before it.
Here is my (lame) attempt so far:
$array = "Swimming,Astronomy,Gardening,Rugby,Landscaping,Football,3D Modelling";
$find = "Football";
$string = magicFunction($find, $array);
echo $string; // $string would = 'Landscaping'
Any help with this would be greatly appreciated.
Many thanks
$terms = explode(',', $array);
$index = array_search('Football', $terms);
$indexBefore = $index - 1;
if (!isset($terms[$indexBefore])) {
trigger_error('No element BEFORE');
} else {
echo $terms[$indexBefore];
}
//PHP 5.4
echo explode(',Football', $array)[0]
//PHP 5.3-
list($string) = explode(',Football', $array);
echo $string;
$array = array("Swimming","Astronomy","Gardening","Rugby","Landscaping","Football","3D" "Modelling");
$find = "Football";
$string = getFromOffset($find, $array);
echo $string; // $string would = 'Landscaping'
function getFromOffset($find, $array, $offset = -1)
{
$id = array_search($find, $array);
if (!$id)
return $find.' not found';
if (isset($array[$id + $offset]))
return $array[$id + $offset];
return $find.' is first in array';
}
You can also set the offset to be different from 1 previous.
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.