I am trying to loop through a string that contains html from a scraped webpage. First I look to return all links that contain the word "result" and then I would like to organize all the links that contain one of four cases, "base", "second", "third" or "latest" and create a fluid array.
Below is what I have come up with but it returns "Warning: strpos(): needle is not a string or an integer". I cannot seem to get the array cases to work.
Any help would be greatly appreciated. Thank you
$key = "results";
$reportKey = array("base", "second", "third","latest");
$keyArray = array();
foreach($html->find('a') as $element){
if (strpos($element->href, $key) !== false){
if (strpos($element->href, $reportKey) !== false){
$keyArray[] = $element->href;
}
}
}
echo "<pre>" . print_r($keyArray) . "</pre> ";
You can't use an array as a needle in strpos. Change second if to:
if (str_replace($reportKey, "", $element->href) === $element->href) {
$keyArray[] = $element->href;
}
strpos() does not allow more than one needle, you can do this:
$key = "results";
$reportKey = array("base", "second", "third","latest");
$keyArray = array();
foreach($html->find('a') as $element)
{
if (strpos($element->href, $key) !== false){
if (
strpos($element->href, $reportKey[0]) !== false
|| strpos($element->href, $reportKey[1]) !== false
|| strpos($element->href, $reportKey[2]) !== false
|| strpos($element->href, $reportKey[3]) !== false
){
$keyArray[] = $element->href;
}
}
}
echo "<pre>" . print_r($keyArray) . "</pre> ";
You could also do your own function, this is only an example:
function multi_strpos($string, $check, $getResults = false)
{
$result = array();
$check = (array) $check;
foreach ($check as $s)
{
$pos = strpos($string, $s);
if ($pos !== false)
{
if ($getResults)
{
$result[$s] = $pos;
}
else
{
return $pos;
}
}
}
return empty($result) ? false : $result;
}
A solution using array_map() and in_array():
$key = 'results';
$reportKey = ['base', 'second', 'third', 'latest'];
$keyArray = [];
foreach($html->find('a') as $element) {
if (false !== strpos($element->href, $key)) {
// I changed the condition here
$pos = array_map(fn($k) => strpos($element->href, $k) !== false, $reportKey);
if (in_array(true, $pos)){
$keyArray[] = $element->href;
}
}
}
$pos will be an array containing booleans based on matches between $element->href and $reportKey items.
Then we check with in_array() if it matched at least one time.
Related
I'm trying to add some text each of an array element. But also I want add that text specific array elements. That's why I used strpos, but this error popped up. Strpos() expects parameter 1 to be string, array given
Here are my codes:
$outline = 'outline/index.html';
$allDivs = [];
$allDivs = $parser->getElementsByTagName('div');
foreach ($allDivs as $div) {
if ($div->getAttribute('class') == 'p-articlelist-content-right') {
if ($div != null) {
$links = $div->getElementsByTagName('a');
if ($links->length > 0) {
$a = $links->item(0);
$link[] = $a->getAttribute('href');
} if(strpos($link, 'https://sumai.tokyu-land.co.jp') === 0) {
foreach($link as $value) {
var_dump($value . $outline);
}
}
}
}
}
what am I missing here? Any idea? Thank you.
strpos operates on strings, $link is an array, as the error states.
I think that this is what you want:
if ($links->length > 0) {
$a = $links->item(0);
$linkRef = $a->getAttribute('href');
if (strpos($linkRef, 'https://sumai.tokyu-land.co.jp') === 0) {
// This will only work for urls that end on '/' but fail for example.com/index.html
$linkRef .= $outline;
}
$link[] = $linkRef;
}
Is it possible to set foreach function more than 2 condition. Example like below:
$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$string = 'NG';
foreach ($stat_cps as $url)
{
if(strpos($string, $url) !== FALSE)
{
echo "One of the field is NG";
return true;
}
}
echo "All field is OK";
What I want is:
if $stat_cps or $acc_idss contains NG then echo "One of the field is NG";
On the above code, it's only working for $stat_cps
*stat_cps and acc_idss is from radio button form.
Anyone can give the suggestion?
"One-line" solution with array_merge, implode and strpos functions:
...
$hasNg = strpos("NG", implode(",", array_merge($stat_cps,$acc_idss)));
...
// check for 'NG' occurance
echo ($hasNg !== false)? "One of the field is NG" : "string 'NG' doesn't exists within passed data";
You can use array_merge to combine both your arrays:
http://php.net/manual/en/function.array-merge.php
$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$merged = array_merge($stat_cps,$acc_idss);
$string = 'NG';
foreach ($merged as $url)
{
if(strpos($string, $url) !== FALSE)
{
echo "One of the field is NG";
return true;
}
}
This will remove duplicate string keys but it doesn't look like that should be an issue here if you just want one match
From you comment try doing
$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$merged = array_merge($stat_cps,$acc_idss);
$match = false;
$string = 'NG';
foreach ($merged as $url)
{
if(strpos($string, $url) !== FALSE)
{
$match = true;
}
}
if($match){
echo "One of the field is NG";
}else{
echo "Everything is OK";
}
$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$process=0;
$string = 'NG';
foreach ($stat_cps as $url)
{
if(strpos($string, $url) !== FALSE)
{
$process=1;
}
}
foreach ($acc_idss as $url2)
{
if(strpos($string, $url2) !== FALSE)
{
$process=1;
}
}
if($process==1){
echo "One of the field is NG";
return true;
}
#header user in_array()
$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$string = 'NG';
foreach ($stat_cps as $url)
{
if(in_array($string, $url) !== FALSE)
{
echo "One of the field is NG";
return true;
}
}
hi i have an array of about 20/30 items big.
i need to have it loop threw the array and echo out only the items with the text p1 in them.
the array looks like so
"lolly","lollyp1","top","topp1","bum","bump1","gee","geep1"
and so on
i have tried to use something like this
foreach ($arr as $value) {
$needle = htmlspecialchars($_GET["usr"]);
$ret = array_keys(array_filter($arr, function($var) use ($needle){
return strpos($var, $needle) !== false;
}));
but all this gives me is a blank page or 1s
how can i have it echo out the items with p1 in them ?
Try This:
$needle = htmlspecialchars($_GET["usr"]);
$rtnArray = array();
foreach ($arr as $value) {
$rtnArray = strpos($value,$needle);
};
return $rtnArray;
If your trying to write directly to the page the lose the $rtnarray and echo:
$needle = htmlspecialchars($_GET["usr"]);
foreach ($arr as $value) {
echo strpos($value,$needle);
};
To only show ones with 'p1' then filter:
$needle = htmlspecialchars($_GET["usr"]);
foreach ($arr as $value) {
$temp = strpos($value,$needle);
if($temp > 1){
echo $value;
}
};
Using a direct loop with string-comparison would be a simple way to go here:
$needle = $_GET['usr'];
$matches = array();
foreach ($arr as $key => $value) {
if (strpos($value, $needle) !== false) {
$matches[] = $key;
}
}
The use of array_filter() in your post should work, pending the version of PHP you're using. Try updating to use a separate / defined function:
function find_needle($var) {
global $needle;
return strpos($var, $needle) !== false;
}
$ret = array_keys(array_filter($arr, 'find_needle'));
Codepad Example of the second sample
i have a code to search for array keys, but only if the message is the exact message, i want it to use strpos so it can detect the message but i don't know how to do it:
My Code:
$message = $_POST['message'];
$responses = array("hi" => "whats up?");
if (array_key_exists($message,$responses)){
$msg = strtolower($message);
$answer = $responses[$msg];
echo $answer;
}
So this only works if the whole posted data was "hi". I want it to use strpos so it can detect hi anywhere, how would i do that?
I'm not 100% sure, but is this what you want?
$foundKey = null;
foreach ($responses as $key => $value) {
if (strpos($message, $key) !== false) {
$foundKey = $key;
break;
}
}
if ($foundKey !== null) {
echo "Found key: " . $responses[$key];
}
Edit:
If you want a case insensitive version, of course you can use this instead:
$foundKey = null;
foreach ($responses as $key => $value) {
if (stripos($message, $key) !== false) {
$foundKey = strtolower($key);
break;
}
}
if ($foundKey !== null) {
echo "Found key: " . $responses[$key];
}
strpos(firststring,secondstring,startposition[Optional]) function is return num.if num>=0 mean second string in first string.
$message = $_POST['message'];
$responses = array("hi" => "whats up?");
if (strpos($message,$responses)>=0){
$msg = strtolower($message);
$answer = $responses[$msg];
echo $answer;
}
I'm trying to do a scrape with SimpleHTMLDom and seem to be running in to a problem.
My code is as follows :
$table = $html->find('table',0);
$theData = array();
foreach(($table->find('tr')) as $row) {
$rowData = array();
foreach($row->find('td') as $cell) {
$rowData[] = $cell->innertext;
}
$theData[] = $rowData;
}
function array_find($needle, array $haystack)
{
foreach ($haystack as $key => $value) {
if (false !== stripos($needle, $value)) {
return $key;
}
}
return false;
}
$searchString = "hospitalist";
$position = array_find($searchString, $theData);
echo ($position);
Which yields the following error:
Warning: stripos() [function.stripos]: needle is not a string or an integer in C:\xampp\htdocs\main.php on line 85
What am I doing wrong?
You have the order of the actual parameters reversed in your call to stripos. See http://us3.php.net/manual/en/function.stripos.php. Just reverse the order of the arguments and that error should be fixed.
Change:
if (false !== stripos($needle, $value)) {
to
if (false !== stripos($value, $needle)) {
From the docs, you should be passing in the needle second, not first. Try this:
function array_find($needle, array $haystack)
{
foreach ($haystack as $key => $value) {
if (false !== stripos($value, $needle)) {
return $key;
}
}
return false;
}
The message is referring to the function argument of stripos and not your variable named $needle.
int stripos ( string $haystack , string $needle [, int $offset = 0 ] )
It is actually complaining about the needle $value