I am very new to php and cannot find out how to fix this. I have a form and want to pass some string to it and have it checked with another file. It is working fine if all the strings are on the same line but as soon as I put in multiple lines of string, it will fail.
I have a php file with the following code:
<?php
echo "<center><form method='post' enctype='multipart/form-data'>";
echo "<b></b><textarea name='texttofind' cols='80' rows='10'></textarea><br>";
echo "<input name='submit' type='submit' style='width:80px' value='Run' />";
echo "</form></center>";
$texttofind = $_POST['texttofind'];
if(get_magic_quotes_gpc()) {
$texttofind = stripslashes($texttofind);
}
$texttofind = html_entity_decode($texttofind);
$s = file_get_contents ("/home/xxxxx/public_html/abc.txt");
if (strpos ($s, $texttofind) === false) {
echo "not found";
}
else
echo "found";
?>
and in abc.txt, I have
dog
cat
rat
Whenever, I open the php page and type in just dog or cat, it will be fine and show 'found' message but when I type multiple lines like 'dog<enter on keyboard>cat' and click submit button, it will return with the 'not found' message.
What is wrong with the code or anyway to adapt it so that it will be able to search multiple lines?
Thank you in advance.
When you place your search words on new lines you are adding characters that do not exist in your comparison file. Eg when you enter...
dog
cat
rat
You are actually sending a string that looks like...
"dog\ncat\nrat"
Where \n means character 13 or the standard non windows new line character. The fix for this depends on what you want to do. You can search for results using PHP's explode function to convert the input string into an array and then get positions for each word...
$inputs = explode("\n", $_POST['field']);
$positions = array();
foreach($inputs as $val)
$positions[] = str_pos($compareTo, $val);
Now $positions should be an array of the str_pos's that where found for each line.
If you are still trying to search that the comparison file has all of the text you just don't care if it is on a new line or not you can simply strip out the new line characters all together (also remove \r just to be safe)
$inputs = str_replace("\n", "", $_POST['field']);
$inputs = str_replace("\r", "", $inputs);
Now inputs would be "dogcatrat". You can use the second argument of str_replace to set a space instead of a \n to get back to the space separated list.
$inputs = str_replace("\n", " ", $_POST['field']);
$inputs = str_replace("\r", "", $inputs);
Yes we are still ignoring \r all together (silly windows). All the same I suggest reading up on how to use array's, explode & implode and str_replace. Many will comment on this and tell you that str_replace is bad and that you should learn regex. As an experienced developer I find very few cases where regex replacements provide any better functionality in simple character replacement and it will cause you to learn a completely new language of commands. For now ignore those who tell you to use regex but definitely learn regex in the near future. You will need it eventually, just not for something of this nature.
http://php.net/manual/en/language.types.array.php
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
http://php.net/manual/en/function.str-replace.php
http://php.net/manual/en/function.preg-match.php
<?php
$values=explode("\n",$txttofind);
foreach($values as $value)
{
if (strpos ($s, $value) === false)
{
echo "$value : not found <br>";
}
else
{
echo "$value : found <br>";
}
}
?>
Related
This is a continuation to the previous case: Removing new lines containing spaces
Now I have a working regular expression:
R^[ ]{3}$
which finds new line and 3 spaces after it.
In PHP I use:
$result = preg_replace('/R^[ ]{3}$/', '', $file);
Which should remove such occurrences. However the output remains unchanged. Consider the following example:
UID(*****************ABCDXXX) ALLOW
UID(*****************EFGHXSX) ALLOW
There are 3 spaces in line 2. End result should be:
UID(*****************ABCDXXX) ALLOW
UID(*****************EFGHXSX) ALLOW
Since I get input from a file, here is how I output the result:
foreach ($result as $key => $value) {
if(!empty($value)) {
echo $value . "<br />";
}
}
I also tried this regular expression but, as you might gathered, it did not work:
\n.{3}$
The new line depends on the platform you run your code in, so on the contents of the file. In Windows this is \r\n, in *Nix \n so we should make \r optional.
$result = preg_replace('/\r?\n[\ ]{3}/', '<br />', $file);
Try with this:
$pattern = "/(<(?!\/)[^>]+>)+(<\/[^>]+>)+/";
$html = preg_replace($pattern, '', $html);
If I have a piece of code that works like this:
$i = 0;
$names = explode(",", $userInput);
foreach($names as $name) {
$i++;
}
It works perfectly, provided the user has placed a comma after each name entered into the html textarea this comes from. But I want to make it more user friendly and change it so that each name can be entered on a new line and it'll count how many lines the user has entered to determine the number of names entered into the field. So I tried:
$i = 0;
$names = explode("\n", $userInput);
foreach($names as $name) {
$i++;
}
But this just gives me "1" as a result, regardless the number of new lines in the textarea. How do I make my explode count new lines instead of basing the count on something specifically entered into the text string?
EDIT Thanks to the people who answered, I don't believe there were any wrong answers as such, just one that suited my original code better than the others, and functioned. I ended up adopting this and modifying it so that numerous blank line returns did not result in artificially inflating the $userInput count. Here is what I am now using:
if(($userInput) != NULL) {
$i = 0;
$names = explode(PHP_EOL, trim($userInput));
foreach($names as $name) {
$i++;
}
}
It trims the empty space from the $userInput so that the remainder of the function is performed on only valid line content. :)
Don't make it complicated, you don't have to explode it into an array, just use this:
(Just count the new line character (PHP_EOL) in your string with substr_count())
echo substr_count($userInput, PHP_EOL);
Try using the PHP end of line constant PHP_EOL
$names = explode(PHP_EOL, $userInput);
A blank string as input:
var_dump(explode("\n", ''));
gives this as a result from a call to explode():
array(1) { [0]=> string(0) "" }
so you could use a ternary statement:
$names = $userInput == '' ? array() : explode("\n", $userInput);
Maybe you can change the explode function with preg_split to explode the user string with a regex
$users = preg_split('/[\n\r]+/', $original);
That's the idea, but I'm not on the computer so I can't test my code.
That regex would split the string if it founds one or more line breaks.
i am using preg_replace for highlighting words in search results. search result sometimes also contains URL, not just text. and some URLs contain key words. then URLs get messed up as preg_replace also changes the URL.
is there any way to ignore URLs in preg_replace?
this is what i use:
$result = preg_replace('!('.$keyword.')!i', '<span style="background: #f00;">$1</span>', $result);
thank you!
Edited..
okay, than is this helpful?
Make your result as array and then check if it contains url?
<?php
$result = "This is Stpartāāa http://google.lv ";
$arr = explode(" ", $result);
foreach($arr as $key => $value) {
if ((strpos($value,'http://') !== false) AND (strpos($value,'www.') !== false)) {
// do nothing
} else {
// do somthing
}
}
?>
Confounded. I've been using the below IF PREG_MATCH to distinguish between words which entire words and words which are parts of other words. It has suddenly ceased to function in this script, and any other script I use, which depend on this command.
The result is it finds parts of words, although you can see it is explicitly told to find only entire words.
$word = preg_replace("/[^a-zA-Z 0-9]+/", " ", $word);
if (preg_match('#\b'.$word.'\b#',$goodfile) && (trim($word) != "")) {
$fate = strpos($goodfile,$word);
print $word ." ";
print $fate ."</br>";
If you only want to read the first word of a line of a text file, like your title suggests, try another method:
// Get the file as an array, each element being a line
$lines = file("/path/to/file");
// Break up the first line by spaces
$words = explode(" ", $lines[0]);
// Get the first word
$firstWord = $words[0];
This would be faster and cleaner than explode and you won't be making any array
$first_word = stristr($lines, ' ', true);
Ok, I'm feeling retarded here,
I have a string like so:
$string = 'function module_testing() {';
or it could be like this:
$string = 'function module_testing()';
or it could be like this:
$string = 'function module_testing($params) {';
or this:
$string = 'function module_testing($params, $another = array())';
and many more ways...
And than I have an array of strings like so:
$string_array = array('module_testing', 'another_function', 'and_another_function');
Now, is there some sort of preg_match that I can do to test if any of the $string_array values are found within the $string string at any given position? So in this situation, there would be a match. Or is there a better way to do this?
I can't use in_array since it's not an exact match, and I'd rather not do a foreach loop on it if I can help it, since it's already in a while loop.
Thanks :)
A foreach loop here is the appropriate solution. Not only is it the most readable but you're looping over three values. The fact that happens within a while loop is a non-issue.
foreach ($string_array as $v) {
if (strpos($string, $v) !== false) {
// found
}
}
You can alternatively use a regular expression:
$search = '\Q' . implode('\E|\Q', $string_array) . '\E';
if (preg_match('!$search!`, $string)) {
// found
}
There are two parts to this. Firstly, there is the | syntax:
a|b|c
which means find a, b or c. The second part is:
\Q...\E
which escapes the contents. This means if your search strings contain any regex special characters (eg () then the regex will still work correctly.
Ultimately though I can't see this being faster than the foreach loop.