Echo words not found in string comparison - php

I have got a variable and an array (can be a variable as well) which need to be compared. I know how to compare two strings, but I don't know how to output the words which haven't been found. Also the words which haven't been found need to be in a variable so that I can use them later on.
$mystring = array('Net 40', 'Net 44', 'Priv 40');
$findme = 'Net 44';
if( strpos($mystring, $findme) !== false ) echo $findme." has been found in the string";
EDIT
I shall rephrase my question: How to compare two variables and output all words which haven't been found.

You could use array_diff to find the words that remain after you have successfully matched a word with one in a list:
$mystring = array('Net40', 'Net44', 'Priv40');
$findme = 'Net44';
echo "<br>list of words before: " . implode(",", $mystring);
$mystring = array_diff($mystring, array($findme));
echo "<br>list of words after: " . implode(",", $mystring);
Output:
list of words before: Net40,Net44,Priv40
list of words after: Net40,Priv40

strpos check that your second parameter is in the first parameter?
e.g.
strpos("This is", "is")
this checks that 'is' is in the string or not. If you want to check the result is in array or not please do as follows
if(in_array($findme,mystring)) echo $findme." has been found in the string";

First, you should not use strpos with an array and a string.
You could make something like this:
$mystring = array('Net 40', 'Net 44', 'Priv 40');
$findme = 'Net 44';
$size = count($mystring)
$notFound = array();
for($i = 0; $i < $size; $i++)
{
if($mystring[$i] === $findme)
{
echo $findme." has been found in the string (actually array)";
}
else
{
array_push($notFound, $mystring[$i]);
}
}
If mystring is actually supposed to be a string this code has to look a little bit different. I went with what you provided.

Solution with arrays. If your have strings, you can convert them to array with explode function.
<?php
$mystring = array('Net40', 'Net44', 'Priv40');
$findme = array('Net44');
$result=array_diff($mystring,$findme);
//$result is an array of elements that was in $mystring but not in $findme
print_r($result);
?>

Haven't been found is a little ambiguous, just be careful:
<?php
$haystack = array('Net40', 'Net44', 'Priv40');
$needles = array('Net44', 'NetBsd');
var_dump(array_diff($haystack, $needles));
var_dump(array_diff($needles, $haystack));
var_dump(array_intersect($haystack, $needles));
Output:
array (size=2)
0 => string 'Net40' (length=5)
2 => string 'Priv40' (length=6)
array (size=1)
1 => string 'NetBsd' (length=6)
array (size=1)
1 => string 'Net44' (length=5)

Related

Why isn't php explode extracting array values

I have some date values (each with a trailing = sign) stored as a &-delimited string.
My $_POST['dates'] string looks like this:
23.08.18=&22.08.18=&21.08.18=
I'm trying the following PHP code to extract the dates before inserting them into my database table. The code is currently not working.
foreach(explode('&', $_POST['dates']) as $value)
{
$value1 = explode('=', $value);
foreach ($value1 as $x) {
}
}
How can I isolate the date values?
The function that you might be looking for is parse_str(). You have a valid query string (well, kind of) with keys but no values, so you merely need to parse it and isolate the keys(dates). Unfortunately, the parser converts your dots to underscores.
Code: (Demo)
$string = '23.08.18=&22.08.18=&21.08.18=';
parse_str($string, $out);
var_export(array_keys($out));
Output:
array (
0 => '23_08_18',
1 => '22_08_18',
2 => '21_08_18',
)
And of course, you can repair the modified date values with str_replace(). See this demo.
Or if you want to disregard parse_str(), you can use just one regex call that divides the string on = followed by an optional &:
Code: (Demo)
$string = '23.08.18=&22.08.18=&21.08.18=';
var_export(preg_split('~=&?~', $string, -1, PREG_SPLIT_NO_EMPTY));
Output:
array (
0 => '23.08.18',
1 => '22.08.18',
2 => '21.08.18',
)
Or without regex, just trim the last = and explode on =&: (Demo)
$string = '23.08.18=&22.08.18=&21.08.18=';
var_export(explode('=&', rtrim($string, '=')));
// same output as preg_split()
<?php
$data = '23.08.18=&22.08.18=&21.08.18=';
//$delimiters has to be array
//$string has to be array
function multiexplode ($delimiters,$string) {
$ary = explode($delimiters[0],$string);
array_shift($delimiters);
if($delimiters != NULL) {
foreach($ary as $key => $val) {
$ary[$key] = multiexplode($delimiters, $val);
}
}
return $ary;
}
$exploded = multiexplode(array("=","&"),$data);
var_dump($exploded);
The result should be:
array (size=3)
0 => string '23.08.18' (length=8)
2 => string '22.08.18' (length=8)
4 => string '21.08.18' (length=8)
We need to use array_filter.
http://php.net/manual/en/function.explode.php
[EDIT] mickmackusa's answer is the right tool for parse url parameters into variables.

Strpos in php not working

I am doing text analysis. I have a table having positive words.The records are being fetched one by one and imploded in an array through mysqli_fetch_array.
while(($rowx = mysqli_fetch_array($resultx,MYSQLI_NUM)))
{
$wordx = implode("", $rowx);
if(strpos($text, $wordx) !== FALSE)
{
$count1 = substr_count($text, $wordx);
$pos_prob += .2 * $count1;
echo "pos prob is".$pos_prob;
}
}
But strpos is not able to match the string that is being fetched from the table.i.e. if text is "It's an excellent book" the if condition is never true. Even though the word excellent is present in the table. And if I hard code the value $wordx as
$wordx='excellent';
Only then it works. Does anyone has any idea why this is happening? :( Any help would be much appreciated :)
I don't understand the need to implode each row. My assumption is that each row has one word.
Simple strpos text matching example:
<?php
$words = array(
'big',
'fat',
'mamma'
);
$text = 'One day fat foo walked to the bar';
$matches = array();
foreach($words as $word) {
if(strpos($text, $word) !== false)
$matches[] = $word;
}
var_dump($matches);
Output:
array (size=1)
0 => string 'fat' (length=3)
Note that this would also match word parts and be case sensitive, so not ideal. For example: 'fat' is contained in the words: 'father', 'infatuated' and 'marrowfat'.

PHP Regex for a specific numeric value inside a comma-delimited integer number string

I am trying to get the integer on the left and right for an input from the $str variable using REGEX. But I keep getting the commas back along with the integer. I only want integers not the commas. I have also tried replacing the wildcard . with \d but still no resolution.
$str = "1,2,3,4,5,6";
function pagination()
{
global $str;
// Using number 4 as an input from the string
preg_match('/(.{2})(4)(.{2})/', $str, $matches);
echo $matches[0]."\n".$matches[1]."\n".$matches[1]."\n".$matches[1]."\n";
}
pagination();
How about using a CSV parser?
$str = "1,2,3,4,5,6";
$line = str_getcsv($str);
$target = 4;
foreach($line as $key => $value) {
if($value == $target) {
echo $line[($key-1)] . '<--low high-->' . $line[($key+1)];
}
}
Output:
3<--low high-->5
or a regex could be
$str = "1,2,3,4,5,6";
preg_match('/(\d+),4,(\d+)/', $str, $matches);
echo $matches[1]."<--low high->".$matches[2];
Output:
3<--low high->5
The only flaw with these approaches is if the number is the start or end of range. Would that ever be the case?
I believe you're looking for Regex Non Capture Group
Here's what I did:
$regStr = "1,2,3,4,5,6";
$regex = "/(\d)(?:,)(4)(?:,)(\d)/";
preg_match($regex, $regStr, $results);
print_r($results);
Gives me the results:
Array ( [0] => 3,4,5 [1] => 3 [2] => 4 [3] => 5 )
Hope this helps!
Given your function name I am going to assume you need this for pagination.
The following solution might be easier:
$str = "1,2,3,4,5,6,7,8,9,10";
$str_parts = explode(',', $str);
// reset and end return the first and last element of an array respectively
$start = reset($str_parts);
$end = end($str_parts);
This prevents your regex from having to deal with your numbers getting into the double digits.

Return part of string

I have an array with strings like:
209#ext-local : SIP/209 State:Idle Watchers 2
208#ext-local : SIP/208 State:Unavailable Watchers 1
How can I echo the state for example Idle or Unavailable?
Thanks.
Using regex it will match any string containing letters and numbers.
$string = '209#ext-local : SIP/209 State:Idle Watchers 2';
preg_match("/State\:([A-Za-z0-9]+)/", $string, $results);
echo $results[1]; // Idle
strpos will search the string to see if it is contains the characters in that exact order.
strpos will not always work if the word idle or unavailable has the possibility to show up in any other way in the string.
You can use the php explode and parse the sting into an array of strings.
exp.
$string = "209#ext-local : SIP/209 State:Idle Watchers 2";
$string = explode(':', $string);
will give you ['209#ext-local ',' SIP/209 State','Idle Watchers 2']. Then if you explode the 3rd entry my ' ' you would get your answer.
$answer = explide(' ', $string[2]);
echo $answer[0];
Assuming your strings are all the same format, you can try splitting the string down using explode(), which returns an array of string, separated by a provided delimiter, like
foreach ($yourStrings as $s) {
$colonSplit = explode(":", $stringToSplit);
$nextStringToSplit = $colonSplit[2];
$spaceSplit = explode(" ", $nextStringToSplit);
$status = $spaceSplit[0];
echo $status;
}
May not be elegant but it should work.
Quick (and dirty) way. Assuming your array contains the full elements you listed above, the array element values do NOT contain 'idle' or 'unavailable' in any other capacity other than what you listed, and you just want to echo out the value and "is idle" or "is unavailable":
//$a being your array containing the values you listed above
foreach ($a as $status) {
if (strpos($status, "Idle") == true)
echo $status . " is idle";
elseif (strpos($status, "Unavailable") == true)
echo "$status" . " is unavailable";
}

PHP str_replace

I'm currently using str_replace to remove a usrID and the 'comma' immediately after it:
For example:
$usrID = 23;
$string = "22,23,24,25";
$receivers = str_replace($usrID.",", '', $string); //Would output: "22,24,25"
However, I've noticed that if:
$usrID = 25; //or the Last Number in the $string
It does not work, because there is not a trailing 'comma' after the '25'
Is there a better way I can be removing a specific number from the string?
Thanks.
YOu could explode the string into an array :
$list = explode(',', $string);
var_dump($list);
Which will give you :
array
0 => string '22' (length=2)
1 => string '23' (length=2)
2 => string '24' (length=2)
3 => string '25' (length=2)
Then, do whatever you want on that array ; like remove the entry you don't want anymore :
foreach ($list as $key => $value) {
if ($value == $usrID) {
unset($list[$key]);
}
}
var_dump($list);
Which gives you :
array
0 => string '22' (length=2)
2 => string '24' (length=2)
3 => string '25' (length=2)
And, finally, put the pieces back together :
$new_string = implode(',', $list);
var_dump($new_string);
And you get what you wanted :
string '22,24,25' (length=8)
Maybe not as "simple" as a regex ; but the day you'll need to do more with your elements (or the day your elements are more complicated than just plain numbers), that'll still work :-)
EDIT : and if you want to remove "empty" values, like when there are two comma, you just have to modifiy the condition, a bit like this :
foreach ($list as $key => $value) {
if ($value == $usrID || trim($value)==='') {
unset($list[$key]);
}
}
ie, exclude the $values that are empty. The "trim" is used so $string = "22,23, ,24,25"; can also be dealt with, btw.
Another issue is if you have a user 5 and try to remove them, you'd turn 15 into 1, 25 into 2, etc. So you'd have to check for a comma on both sides.
If you want to have a delimited string like that, I'd put a comma on both ends of both the search and the list, though it'd be inefficient if it gets very long.
An example would be:
$receivers = substr(str_replace(','.$usrID.',', ',', ','.$string.','),1,-1);
An option similar to Pascal's, although I think a bit simipler:
$usrID = 23;
$string = "22,23,24,25";
$list = explode(',', $string);
$foundKey = array_search($usrID, $list);
if ($foundKey !== false) {
// the user id has been found, so remove it and implode the string
unset($list[$foundKey]);
$receivers = implode(',', $list);
} else {
// the user id was not found, so the original string is complete
$receivers = $string;
}
Basically, convert the string into an array, find the user ID, if it exists, unset it and then implode the array again.
I would go the simple way: add commas around your list, replace ",23," with a single comma then remove extra commas. Fast and simple.
$usrID = 23;
$string = "22,23,24,25";
$receivers = trim(str_replace(",$usrID,", ',', ",$string,"), ',');
With that said, manipulating values in a comma separated list is usually sign of a bad design. Those values should be in an array instead.
Try using preg:
<?php
$string = "22,23,24,25";
$usrID = '23';
$pattern = '/\b' . $usrID . '\b,?/i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>
Update: changed $pattern = '/$usrID,?/i'; to $pattern = '/' . $usrID . ',?/i';
Update2: changed $pattern = '/' . $usrID . ',?/i to $pattern = '/\b' . $usrID . '\b,?/i' to address onnodb's comment...
Simple way (providing all 2 digit numbers):
$string = str_replace($userId, ',', $string);
$string = str_replace(',,','', $string);

Categories