I have an if in a foreach in a while loop. I'm searching for a string in another string of text.
$base = 'someurl';
$url = $base;
while(1){
$json = json_decode(file_get_contents($url));
$more = $json->next_page;
$next = $json->next_page_number;
if($more){
$url = $base.'&page='.$next;
}else{
break;
}
foreach($json as $data){
$c = $data->text; // search in
$s = 'string';
$t = 'prefix1'.$s; // search for
$m = 'prefix2'.$s; // search for
if( (strpos($c, $t) || strpos($c, $m)) !== false ){
echo '<p>hello, i found one or more ($t and/or $m) of the search criteria in the text string $c .</p>';
break;
}
}
}
The problem is that I get the echo from the if statement twice :(
What I want to achieve is to only make the echo happen ONCE, if $t and/or $m is present in $c.
Well, i guess you're receiving the echo twice because you found 2 records that match your condition, is that possible?
If so, and you only want to check that your condition matches at least once on the array, you could break the foreach after you found your first match, like:
if( ( strpos( $c, $t ) || strpos( $c, $m ) ) !== false ){
echo '<p>hello, I was told I was true</p>';
break;
}
OK, so found a working solution for my particular problem (although I'm still not clear as to why the if statements response got echoed twice?).
Using preg_match instead of strpos gave me a working solution :)
if(preg_match('('.$t.'|'.$m.')', $c) === 1){
// tis' the truth echoed thru eternity
}
Related
Before I got this answer
preg_replace("~(?<=$str&&).*~", '7', $str);
which is good but what if within the array I have a similar string mary&&5 and rosemary&&5 and I stricktly want to change only mary&&5 and not disturb the other array, is it posible? and how?
The question before was:
`$array = array("josh&&3", "mary&&5", "cape&&4", "doggy&&8", etc..);`
and I know only the string before && which is username. $str = "mary&&"; Note that I don't know what is after &&
I want to know whether exist or not within the array, and if exist change the value to something new like mary&&7
`$isExists = preg_replace("some","some", $array);
if ($isExists){
echo "Its exists";
} else {
echo "Not exixts"
} ;`
How can I change the portion of the value after && in mary&&5 or completely change mary&&5 to mary&&7 since I don't know before hand the value mary&&5?
Thanks for your answer :)
`$name = "mary";
$res = "7";
$str = array("josh&&3", "mary&&5", "cape&&4", "doggy&&8","rosemary&&5");
for ($i = 0; $i < count($str); ++$i) {
$r = preg_replace("~(?<=$name).*~",$res, $str);}`
$arr = array('josh&&3', 'mary&&5', 'cape&&4', 'doggy&&8', 'rosemary&&5');
$name = 'mary';
$number = '7';
$replacement = $name . '&&' . $number;
So, a way without regex:
foreach($arr as $k=>$v) {
if (explode('&&', $v)[0] === $name)
$arr[$k] = $replacement;
}
( or you can use strpos($v, $name . '&&') === 0 as condition)
a way with regex:
$arr = preg_filter('~\A' . $name . '&&\K.*~', $number, $arr);
(where \K removes all on the left from the match result, so the name and && aren't replaced)
How would I go about ordering 1 array into 2 arrays depending on what each part of the array starts with using preg_match() ?
I know how to do this using 1 expression but I don't know how to use 2 expressions.
So far I can have done (don't ask why I'm not using strpos() - I need to use regex):
$gen = array(
'F1',
'BBC450',
'BBC566',
'F2',
'F31',
'SOMETHING123',
'SOMETHING456'
);
$f = array();
$bbc = array();
foreach($gen as $part) {
if(preg_match('/^F/', $part)) {
// Add to F array
array_push($f, $part);
} else if(preg_match('/^BBC/', $part)) {
// Add to BBC array
array_push($bbc, $part);
} else {
// Not F or BBC
}
}
So my question is: is it possible to do this using 1 preg_match() function?
Please ignore the SOMETHING part in the array, it's to show that using just one if else statement wouldn't solve this.
Thanks.
You can use an alternation along with the third argument to preg_match, which contains the part of the regexp that matched.
preg_match('/^(?:F|BBC)/', $part, $match);
switch ($match) {
case 'F':
$f[] = $part;
break;
case 'BBC':
$bbc[] = $part;
break;
default:
// Not F or BBC
}
It is even possible without any loop, switch, or anything else (which is faster and more efficient then the accepted answer's solution).
<?php
preg_match_all("/(?:(^F.*$)|(^BBC.*$))/m", implode(PHP_EOL, $gen), $matches);
$f = isset($matches[1]) ? $matches[1] : array();
$bbc = isset($matches[2]) ? $matches[2] : array();
You can find an interactive explanation of the regular expression at regex101.com which I created for you.
The (not desired) strpos approach is nearly five times faster.
<?php
$c = count($gen);
$f = $bbc = array();
for ($i = 0; $i < $c; ++$i) {
if (strpos($gen[$i], "F") === 0) {
$f[] = $gen[$i];
}
elseif (strpos($gen[$i], "BBC") === 0) {
$bbc[] = $gen[$i];
}
}
Regular expressions are nice, but the are no silver bullet for everything.
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']);
}
I want to make a PHP script that takes a PHP GET variable $_GET[q] made up of many different words or terms and checks to see if it contains any "keywords" that are stored in an array. An example of this would be It could look like "What time is it in San Francisco". I would want the script to pick up on "time" and "san francisco" as an example. I have played about with using
if(stripos($_GET[q],'keyword1','keyword2'))
but haven't had much luck.
Does anyone know how I could do this?
I hope everyone can understand what I am trying to describe.
You can make an array of keywords, then loop though until you find a match.
$array = array('keyword1', 'keyword2');
$found = false;
foreach($array as $x){
if(stripos($_GET['q'], $x) !== false){
$found = true;
break;
}
}
if($found){
}
UPDATE: If you want to match ALL keywords, you can do this instead:
$array = array('keyword1', 'keyword2');
$found = true;
foreach($array as $x){
$found &= stripos($_GET['q'], $x) !== false;
}
if($found){
}
DEMO: http://codepad.org/LaEX6m67
UPDATE 2: Because I'm crazy and like one-liners, you can do this in PHP 5.3+:
$array = array('keyword1', 'keyword2');
$val = $_GET['q'];
$found = array_reduce($array, function($x, $v) use($val){
return $x && stripos($val, $v) !== false;
}, true);
if($found){
}
DEMO: http://codepad.viper-7.com/Y48sHR
foreach($arr as $value){
if(stripos($_GET[q],$value){
do stuff
}
}
Use in_array function:
// assuming $arr is your array of keywords
if (in_array($_GET['q'], $arr))
echo "found a match\n";
EDIT: Based on your comments here is the code you can use, that works without any loop:
$arr = array('keyword1', 'keyword2', 'keyword3');
$brr = array_map(create_function('$m', 'return "/\b" . $m . "\b/";'), $arr);
if ($_GET['q'] !== preg_replace($brr, '', $_GET['q']))
echo "found a match\n";
else
echo "didn't find a match\n";
I don't want to echo string if before string is similar to current string. Let's say our strings are,
$strings = array("software","software","game","antivirus");
My difference function,
function ($val1,$val2) {
similar_text($val1,$val2,$percent);
if ($percent>83) {
// should not echo. But don't know how to do.
}
}
But I don't know how can I do it. I guess it should be with using for each.
Try something like this:
$strings = array("software","software","game","antivirus");
$lastString = '';
foreach ($strings as $string) {
similar_text($lastString, $string, $percent);
if ($percent < 83) {
echo "$string<br />";
$lastString = $string;
}
}
If you don't understand some part of it, leave a comment and I will clarify.
Edit:
I moved the $lastString = $string; inside the condition.
Consider the following list of strings:
$strings = array("software","sofware","sofwart","ofwart","fwart","wart","warts");
Leaving the $lastString assignment outside of the loop would only print software even though lots of the words are very very different software they are not so different from the previous word.
Moving it inside actually gives the output :
software
sofwart
wart
$strings = array("software","software","game","antivirus");
$previous = '';
foreach ($strings as $string) {
if ($string===$previous) {
continue;
} else {
echo $string;
$previous = $string;
}
}
But I think it's better to do it with for like this (it should be faster):
$strings = array("software","software","game","antivirus");
$num = count($strings);
for ($i=0;$i<$num;$i++) {
if ($strings[$i]===$strings[$i-1] && $i!==0) {
continue;
} else {
echo $strings[$i];
}
}
Btw I totally did't get what the $percent means..
An approach using array_filter() (assumes >= 5.3):
$strings = array('software', 'software', 'game', 'antivirus');
$filtered = array_filter($strings, function($curr) {
static $prev;
similar_text($prev, $curr, $percent);
$prev = $curr;
if ($percent < 83) {
return $curr;
}
});
print_r($filtered);
Yields:
Array
(
[0] => software
[2] => game
[3] => antivirus
)
Hope this helps. Actually, I never knew about similar_text() until now. Pretty interesting function. Thanks :)