Check if string contains any value of an array? - php

$search=array("<",">","!=","<=",">=")
$value="name >= vivek ";
I want to check if $value contains any of the values of the $search array. I can find out using foreach and the strpos function. Without resorting to using foreach, can I still find the answer? If so, kindly help me to solve this problem.

Explode $value and convert it into array and then use array_intersect() function in php to check if the string does not contain the value of the array.Use the code below
<?php
$search=array("<",">","!=","<=",">=");
$value='name >= vivek ';
$array = explode(" ",$value);
$p = array_intersect($search,$array);
$errors = array_filter($p);
//Check if the string is not empty
if(!empty($errors)){
echo "The string contains an value of array";
}
else
{
echo "The string does not containe the value of an array";
}
?>
Test the code here http://sandbox.onlinephpfunctions.com/code/7e65faf808de77036a83e185050d0895553d8211
Hope this helps you

Yes, but it will require you to re structure your code.
$search = array("<" => 0, ">" => 1,"!=" => 2,"<=" => 3,">=" => 4);
$value = "name => vivek ";
$value = explode(" ", $value);
foreach($value as $val) {
// search the array in O(1) time
if(isset($search[$val])) {
// found a match
}
}

Use array_map() and array_filter()
function cube($n)
{
$value="name => vivek ";
return strpos($value, $n);
//return($n * $n * $n);
}
$a = array("<",">","!=","<=",">=");
$value="name => vivek ";
$b = array_map("cube", $a);
print_r($b);
$b = array_filter($b);
print_r($b);

$search = array("<",">","!=","<=",">=");
$value="name => vivek ";
foreach($value as $searchval) {
if(strpos($value, $searchval) == false)
{
echo "match not found";
}
else
{
echo "match found";
}
}

Here's a solution using array_reduce:
<?PHP
function array_in_string_callback($carry, $item)
{
list($str, $found) = $carry;
echo $str . " - " . $found . " - " . $str . " - " . $item . "<br/>";
$found |= strpos($str, $item);
return array($str, (boolean) $found);
}
function array_in_string($haystack, $needle)
{
$retVal = array_reduce($needle, "array_in_string_callback", array($haystack, false));
return $retVal[1];
}
$search=array("<",">","!=","<=",">=");
$value="name >= vivek ";
var_dump(array_in_string($value, $search));
?>

My first inclination was to solve the problem with array_walk() and a callback, as follows:
<?php
$search=array("<",">","!=","<=",">=");
$value = "name >= vivek ";
function test($item, $key, $str)
{
if( strpos($str, $item) !== FALSE ) {
echo "$item found in \"$str\"\n";
}
}
array_walk($search, 'test', $value);
// output:
> found in "name >= vivek "
>= found in "name >= vivek "
Live demo: http://3v4l.org/6B0WX
While this solves the problem without a foreach loop, it answers the question with a "what" rather than a "yes/no" response. The following code directly answers the question and permits answering the "what" too, as follows:
<?php
function test($x)
{
$value="name >= vivek ";
return strpos($value, $x);
}
$search = array("<",">","!=","<=",">=");
$chars = array_filter( $search, "test" );
$count = count($chars);
echo "Are there any search chars? ", $answer = ($count > 0)? 'Yes, as follows: ' : 'No.';
echo join(" ",$chars);
// output:
Are there any search chars? Yes, as follows: > >=
Live demo: http://3v4l.org/WJQ5c
If the response had been negative, then the output is 'No.' followed by a blank space.
A key difference in this second solution compared to the first, is that in this case there is a return result that can be manipulated. If an element of the array matches a character in the string, then array_filter adds that element to $chars. The new array's element count answers the question and the array itself contains any matches, if one wishes to display them.

Related

How To Check If A Specific Character Exists In A String In A PHP?

Im creating a function to check whether a string contains a specific character prefixed,I need to validate the text based on two conditions.
1.if the string contains character + prefixed ,i have to show the text in output without prefix +.
eg:
"we have dinner +today"
output:
"we have dinner today"
2.if the string contains character - prefixed ,i have to show the text in output removing the whole text prefixed with -.
eg:
"we have dinner -today"
output:
"we have dinner".
I will pass an extra parameter called length in this function ,If the string length is less than the given length then the string will be removed.
eg:
length=4;
eg:
"we have dinner -today"
output:
"have dinner".
eg:
"we have dinner +today"
output:
"have dinner today".
The function i have created so far is
$fulltext="-through the +use of the +tab +key";
$length=4;
function checkstring($fulltext,$length)
{
$stringArray = explode(" ", $fulltext);
foreach ($stringArray as $value)
{
if(strlen($value) < $length)
$fulltext= str_replace(" ".$value." " ," ",$fulltext);
}
return $fulltext;
}
print_r(checkstring($fulltext,$length));
The output should be "use tab key"
You can iterate over the words and check if the conditions are checked to keep in the sentence.
$fulltext = "-through the +use of the +tab +key";
$length = 4;
function checkstring($fulltext, $length)
{
$words = preg_split('~\s~',$fulltext);
$remains = [];
foreach ($words as $word)
{
if (strpos($word, '-') === 0) {
continue;
}
if (strpos($word, '+') === 0) {
$word = substr($word, 1);
}
elseif (strlen($word) <= $length) {
continue;
}
$remains[] = $word;
}
return trim(implode(' ', $remains));
}
echo checkstring($fulltext, $length);
Output :
use tab key
View the online demo.
You can use this
if(ctype_alnum($fulltext)) {
echo 'Does not contain symbols';
} else {
echo 'Contains symbols';
}
One way is to use regular expressions to find matching string with correct length and prefixed symbol. If the prefix equals '+' you can then replace the match with string without prefix.
Take a look at preg_replace_callback() and example below.
/* a unix-style command line filter to convert uppercase
* letters at the beginning of paragraphs to lowercase */
<?php
$line = "<p>Start of the paragraph</p>";
$line = preg_replace_callback(
'|<p>\s*\w|',
function ($matches) {
return strtolower($matches[0]);
},
$line
);
echo $line;
?>
function checkstring($fulltext, $length)
{
$stringArray = explode(" ", $fulltext);
foreach ($stringArray as $value) {
if ($value[0] == "-") {
$fulltext = str_replace($value, " ", $fulltext);
} else if ($value[0] == "+") {
$fulltext = str_replace($value, substr($value, 1), $fulltext);
}
if (strlen($value) < $length)
$fulltext = str_replace(" " . $value . " ", " ", $fulltext);
}
return $fulltext;
}
Here is the complete function
Using regex
function checkstring(string $fulltext,int $length){
$matches = []; preg_match_all('/[+|-](.[\w]+)/',$fulltext,$matches);
$text = "";
if(isset($matches[1]) && count($matches[1]) > 0)
for($i=0;$i<count($matches[1]);$i++)
if($matches[0][$i][0] == "+" && ($matches[0][$i][0] == "+" && strlen($matches[1][$i]) < $length))
$text .= $matches[1][$i] . " ";
return trim($text);
}
$fulltext="-through the +use of the +tab +key";
$length = 4;
echo checkstring($fulltext,$length);
Output
use tab key

PHP Array output with comma and "or" [duplicate]

This question already has answers here:
Implode an array with ", " and add "and " before the last item
(16 answers)
Closed 7 years ago.
My php output is an array. Like:
$array = array('banana', 'mango', 'apple');
Now If output is only 'Banana' then it will show simply
Banana
If output is 'banana' & 'mango' or 'apple' the i want to show like
Banana or Mango
If output is all.. then result will be shown
Banana, Mango or Apple
Now I can show result with comma using this code
echo implode(",<br/>", $array);
But How to add or ??
Please help.
Try this:
<?php
$array = array('banana','mango','apple');
$result = '';
$maxelt = count($array) - 1;
foreach($array as $n => $item) {
$result .= ( // Delimiter
($n < 1) ? '' : // 1st?
(($n >= $maxelt) ? ' or ' : ', ') // last or otherwise?
) . $item; // Item
}
echo $result;
use the count and map with that like
$count = count($your_array);
if($count > 3){
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
$last = $your_array[$key];
unset($your_array[$key]);
echo implode(",<br/>", $your_array)."or"$last;
}
you can replace last occurrence of a string in php by this function:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
$array = array('banana', 'mango', 'apple');
$output = implode(", ", $array);
echo $output = str_lreplace(',',' or',$output);
$count = count($array);
if( $count == 1 ) {
echo $array[0];
} else if ( $count == 2 ) {
echo implode(' or ', $array);
} else if ( $count > 2 ) {
$last_value = array_pop( $array );
echo implode(', ', $array).' or '.$last_value;
}
please try below Code :
$array = array('banana','mango','apple');
$string = null;
if(count($array) > 1){
$string = implode(',',$array);
$pos = strrpos($string, ',');
$string = substr_replace($string, ' or ', $pos, strlen(','));
}elseif(count($array) == 1){
$string = $array[0];
}
echo $string;

PHP search letter in array within array

I have an array for example
$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
Now what I want is to get rid all the same letter from $arr1 to $arr2 and count the remaining.
example output:
oe //total count is 2
You could do something like this,
$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
$uniquecounts = array_count_values(array_merge($arr1, $arr2));
foreach($uniquecounts as $char => $count) {
if($count == 1) {
echo $char . ' is unique' . "\n";
}
}
This combines your two arrays of individualized characters and compares them for only one occurrence of the character. Take a look at the manual for how to use array_count_values, http://php.net/manual/en/function.array-count-values.php, in the future.
Output:
o is unique
e is unique
Update:
<?php
$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
$uniquecounts = array_count_values(array_merge($arr1, $arr2));
$unqiues = '';
foreach($uniquecounts as $char => $count) {
if($count == 1) {
$unqiues .= $char;
}
}
echo $unqiues . ' ' . strlen($unqiues);
Output:
oe 2
function deduce($string1, $string2) {
$result = array();
foreach (count_chars($string2 . $string1, 1) as $i => $val) {
if($val == 1) {
$result[] = chr($i);
}
}
return $result;
}
I've encountered this one before and what I did was this.

Most occurred letter in a string using php function

i have string AABBBCCCDABBAACBB , in this i need to find the most occurrence of Character , how can i find this??
in above string it should return 7 ad B comes 7 times i.e max.
$str = "AABBBCCCABB";
$strArray = count_chars($str,1);
foreach ($strArray as $key=>$value)
{
echo "The character <b>'".chr($key)."'</b> was found $value time(s)<br>";
//$highest=chr($key);
if(isset($highest) && $highest>chr($key))
{
$highest=chr($key);
}
}
echo "<br/><br/>Highest value is ::".$highest;
above code i tried,
i tried but functionality is not perfect , which function of php i should use?
You don't need a loop for this. Use array_search() to find the key of the most repeated value, and use chr() on it:
$str = "AABBBCCCDABBAACBB";
$strArray = count_chars($str,1);
echo chr(array_search(max($strArray), $strArray));
Output:
B
Demo!
$string="AABBBCCCABB";
foreach (str_split($string) as $s){
if (isset($counts[$s])) continue;
$counts[$s]=substr_count($string, $s);
echo "The character <b>'" . $s . "'</b> was found ".$counts[$s]." time(s)<br>";
}
$maxs=array_keys($counts, max($counts));
echo "Highest value is ::'".$maxs[0];
Solution for your code by your way:
$str = "AABBBCCCABB";
$strArray = count_chars($str,1);
$highest = $str[0];
$times = 0;
foreach ($strArray as $key=>$value){
echo "The character <b>'".chr($key)."'</b> was found $value time(s)<br>";
//$highest=chr($key);
if($times < $value)
{
$times = $value;
$highest=chr($key);
}
}
echo "<br/><br/>Highest value is ::".$highest;
But answer of Alma Do is better to use.
You could also use the max() function:
$str = "AABBBCCCABB";
$strArray = count_chars($str,1);
$highest = max($strArray);
foreach ($strArray as $key=>$value) {
echo "The character <b>'" . chr($key) . "'</b> was found $value time(s)<br>";
}
echo "<br/><br/>Highest value is ::" . $highest;
Try this solution, hope this helps you to solve.
$string = "AABBBCCCABB";
$letters = array_count_values(str_split($string));
$val = array_search(max($letters), $letters);
echo $val;
Try this..
echo maxCountChar("AABBBCCCDABBAACBB");
function maxCountChar($string){
foreach (str_split($string) as $s){
$counts[$s]=substr_count($string, $s);
}
$maxs=array_keys($counts, max($counts));
$num = substr_count($string, $maxs[0]);
return "The character <b>$maxs[0]</b> was found <b>$num</b> times";
}
Output
The character B was found 7 times

php replace non matches from two arrays

How do you replace all non matches from one array that are not defined within the other array, i have kind of got working but its not exactly right. as i will show you.
the result is, but wrong.
- - £ 8 - - - - - - - -
The required result should be
£ 8 - -
this is how my code is
$vals_to_keep = array(8, 'y', '£');
$replace_if_not_found = array('£', 8, '#', 't'); // replace if not in above array
$result = '';
foreach ($replace_if_not_found as $d) {
foreach ($vals_to_keep as $ok) {
if(strcmp($d, $ok) == 0){
$result .= $d . " ";
}else
$result .= str_replace($d, $ok ,'-') . " ";
}
}
echo $result;
use in_array http://php.net/manual/en/function.in-array.php
foreach ($replace_if_not_found as $d) {
if (in_array($d, $vals_to_keep))
$result .= $d . " ";
else
$result .= str_replace($d, $ok ,'-') . " ";
}
You could loop over all of the items in $replace_if_not_found replacing them with -, or not, as appropriate.
Using closure in PHP 5.3 or above
$result = array_map(function($item) use ($vals_to_keep) {
return in_array($item, $vals_to_keep, TRUE) ? $item : '-';
}, $replace_if_not_found);
echo implode(' ', $result);
Using a foreach loop
$result = array();
foreach ($replace_if_not_found as $item) {
if (in_array($item, $vals_to_keep, TRUE)) {
$result[] = $item;
} else {
$result[] = '-';
}
}
echo implode(' ', $result;

Categories