array_search/in_array can't find string - php

I have the following code
$checkarray = unserialize(file_get_contents('serialized.txt'));
var_dump($checkarray);
foreach($checkarray as $_index => $_image )
{
echo strval($_index)." = ".var_dump($_image)."<br>";
}
var_dump(array_search('pirates_of_love_and_kingdoms.jpg',$checkarray));
var_dump(in_array('pirates_of_love_and_kingdoms.jpg',$checkarray));
the contents of 'serialized.txt' can be found here (http://textuploader.com link, not a download link, will need to copy and paste into new file if you want to use it)
the first var_dump output the array however because i have xdebug not the entire array is outputted, i'm not looking to get this fixed, it just confirms that the file was imported and unserialize correctly, the loop outputs everything in the array confirming that every value is a string (thanks to xdebug), the final 2 var_dumps are to output the results of the functions.
when i run my code, both var_dumps output false, however if i use the browser to search for the text i do find it so i know it's in the array.
I know that array_search returns the key in the array if the needle is found while in_array returns true if the needle is found and both will return false if the needle can't be found, however i do not get how neither can find it when i can confirm it's outputted in the loop and in my serialized.txt file at the same index as what is specified in the file.
i have already checked the basics, white spaces, new lines, casing in both what is outputted on the screen and in the file, can anyone explain to me what i have done wrong?

The line breaks at the end of each line are causing problems for you. Do a trim inside your foreach:
$checkarray = unserialize(file_get_contents('serialized.txt'));
var_dump($checkarray);
foreach($checkarray as $_index => $_image )
{
$checkarray[$_index] = trim($_image);
echo strval($_index)." = ".var_dump($_image)."<br>";
}
var_dump(array_search('pirates_of_love_and_kingdoms.jpg',$checkarray));
var_dump(in_array('pirates_of_love_and_kingdoms.jpg',$checkarray));

Related

Array content, stored in variable, gets cut off

I am trying to put content into an array. The content, around 100 urls, is already stored in a variable that I call $arraycontents which is formatted with ",". For some reason the array get cuts of when I do this but it works when I put in the urls manually. Very annoying problem.
Here is the code:
$arraycontents = '"http://archive.org/wayback/available?url=' . implode('","http://archive.org/wayback/available?url=',$matches[0]). '"';
$urls = array($arraycontents);
in the error message I get it looks like the array is cut off.
$matches[0] contains "urls" already an array, so prefix all with (if I guess right what OP wants)
$urls = array_map(function($m) {
return 'http://archive.org/wayback/available?url='.$m;
},$matches[0]);

PHP: Check URL against array of badwords, and output any found

I have a database which contains the results of logged network traffic, and I'm building a simple log viewer frontend in PHP. I need to check each URL and see if it contains any of the 'bad words' in an external 'badwords.txt' file, then echo which ones, and color the table row red (the easy bit!)
Thus far I have loaded the badwords.txt file into an array, and fetched the URL from the database. Here is the portion of my code where I am trying to get a positively identified 'bad' url. I ideally want to output which badwords were found, but have simplified everything to just try and get it to work for now.
// Load the badwords file into an array
$words = file('badwords.txt');
//$row[3] is the URL fetched from the database
$testURL = $row[3];
foreach ($words as $phrase) {
if (strrpos($testURL, $phrase)) {
echo "FOUND";
}
}
This is not working for me, and never outputs FOUND, even when the url definitely contains a bad word. I have checked that my $words array is populated correctly with all the badwords, and I have checked that the $testURL is not empty etc.
Can anyone help please? :) I'd be really grateful for any assistance - I have read through so many StackExchange posts on similar topics, but none seem to work for my case.
Thank you!
Words array contains newline symbol, so strpos never works. Remove them
$words = file('badwords.txt', FILE_IGNORE_NEW_LINES);
Since strrpos() returns numeric position of needle, and boolean false, so code should be
<?php
// Load the badwords file into an array
$words = file('words.txt', FILE_IGNORE_NEW_LINES);
//$row[3] is the URL fetched from the database
$testURL = row[3];
foreach ($words as $phrase) {
if (strrpos($testURL, $phrase)>-1) {
echo "FOUND";
}
}

Files Read and put it to in a loop with many to one relation Ruby

I am trying to assign a variable in watir method after reading the text file. I am using the following method. In loop, first loop is working fine but in second loop it shows error.
My code is as follows:
file = File.new("states.txt", "r")
contentsArray=[] # start with an empty array
file.each_line {|line|
contentsArray.push line
}
browser = Watir::Browser.new
browser.goto 'http://example.com'
for y in 0..2 do
puts state=contentsArray[y]
browser.text_field(:name => 'Keyword').set 'Pediatrics'
browser.text_field(:name => 'Address').set "#{state}"
browser.div(:id => 'uniform-formSearchDoctorBtn').fire_event :click
browser.link(:class => "start-over pull-right gen-button").click
end
following error occurred .
`assert_exists': unable to locate element, using {:id=>"uniform-formSearchDoctorBtn", :tag_name=>"div"} (Watir::Exception::UnknownObjectException)
Where as when I am putting an static array in place of contentsArray
contentsArray=Array['AL','AK','AZ','AR']
Then code works fine.
Yes Got the solution with the help of justin.
if you output the contentsArray, you will likely get
["AL\n", "AK\n", "AZ\n", "AR"]
Notice that there is a "\n", which is the line break character. You want to strip the line break by changing contentsArray.push line to
contentsArray.push line.strip
For more details, see the question How do I remove carriage returns with Ruby? – Justin Ko

Replace strings in a file from an array in PHP

This is a tricky one...I am trying to replace some strings in a file that i hold in array.
Because there are a lot of files...i've been trying to find the fastest way possible.
I tried this (which worked) but it was slow.
First parsed all the files and got an array of the values i want to
change (lets say 500).
Then I wrote a foreach loop to parse through the files one by one.
Then inside that, another foreach loop to go through the values one by one
preg_replacing the file for any occurrences of the array value.
This takes forever though cause not all files need to be parsed with 500 array elements.
So i am changing the code now like this:
Parse every file and make an array of the values i want to replace.
Search the file again for all the occurrences for each array value and replace it.
Save the file
I think this will be much faster that the old way...The problem i am having though now is with the read/write loop, and the array loop...
I want to do this as fast as possible...cause there will be a lot of files to parse and some have 100+ values.
So far i got this in a function.
function openFileSearchAndReplace($file)
{
$holdcontents = file_get_contents($file);
$newarray = makeArrayOfValuesToReplace($holdcontents);
foreach ($newarray as $key => $value) {
$replaceWith = getNewValueFor($value);
$holdcontent = preg_replace('/\\b'.$value.'\\b/', $replaceWith, $holdcontents);
}
file_put_contents($file, $holdcontent, LOCK_EX); //Save and close
}
Now, this doesnt work...it just changes 1 value only because i have file_put_contents and file_get_contents outside of the foreach. (Not to mention that it replaces values that it shouldnt replace. Probably cause the read/write are outside of the loop.) I have to put them inside to work..but thats gonna be slow..cause it take 3-4seconds per file to do the change since there are a lot of elements in the array.
How can i "Open the file", "Read it", "Change ALL values first", "Then save close the file", so i can move to the next.
EDIT:
Maybe i am not explaining it well i dont know...or is this too complicated....I have to parse the array of values...there is no way i can avoid that...but instead of (In every loop), i open the file search and replace 1 value, close the file.....I want to do this:
Open the file, get the content in an array or string or whatever. For all the values i have keep replacing the text with the equivalent value, and when all the values are done...that array or string write to the file. So i am only opening/closing the file once. Instead of waiting for php to read/write/close all the time.
-Thanks
How about just using str_replace(mixed $search , mixed $replace , mixed $subject)?
You can have an array of search strings which will be replaced by their corresponding item in the replace array and as the PHP manual says:
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().
Also just close the file and reopen it with mode 'w'. File will be truncated to 0 length
Added Edit
$fileContents = file_get_contents("theFile");
$search = array('apples', 'oranges');
$replace = array('pears', 'lemons');
$newContents = str_replace($search, $replace, $fileContents);
$handle = fopen("theFile","w");
fwrite($handle, $newContents);
fclose($handle);
That's it your file has all the old strings replaced with new ones.
There is no solution to the problem. file_get_contents and file_put_contents simply doesnt work like that.
I appreciate everyone's attention to the problem.

Unexpected 'undefined offset' error in PHP

In this project I am sifting through non formatted HTML code and looking for a specific value, below is a section of code from a paragraph deconstruction function. I am using preg_replace to get rid of any unneeded html code until I end up with a small array of variables delimited by the html tag. Below is the section of logic I am having a problem with. For some reason I am receiving an un-defined offset 5 error when attempting to print the 5th position of the array $pieces. I am using the explode function to create the array and have included the chunk of html code I am running explode on.
$new_broken_var = preg_replace($para_search, $para_replace, $para_subject);
$pieces = explode("<br>", $new_broken_var);
echo $pieces[5];
//upon echoing $new_broke_var I received the below html as it's value
//<font face="Arial" size="2">For 06/01/13 to 06/30/13<br>
//Report Generated: Thursday, July 11, 2013<br>Unit: 204 <br>
//Driver:<br>Owner:<br>Number of Trips: 27<br>Fuel Type: Diesel</font>
//creates an array using <br> as it's delimiter on the commented code above
//the variable we want is in position number 5 within the array. and confirmed via print_f($pieces);
It's a good practice to check whether the requested index actually exists in your array.
if (isset($pieces[5])) {
echo $pieces[5];
}
The index may not exist for various reasons, but in your case it just seems your paragraph is empty, causing explode() to return an array with a single element.

Categories