I got a problem with my small php script.
My code should function as a follow-/unfollow-system like in forum softwares (for example XenForo).
So what my script does is that it searches for a user in a string and if the name is found it removes the name of the user in the string. But my problem is that the script can not search for the name and comma for some reason because I try to remove the comma from the string aswell.
Any help is appreciated, thanks in advance :)
Example:
Peter is following Franz and George but he want's to unfollow George
Script:
<?php
$user1 = "Peter";
$following1 = "Franz, George";
$user2 = "Franz";
$following2 = "Peter, George";
$user3 = "George";
$following3 = "Peter, Franz";
//
//
//
if (strpos($following1, $user3) == true) {
echo "Can remove follow.";
if (strpos($following1, ", $user3")) {
$user3 = ", $user3";
$fNew = str_replace($user3, "", $following1);
echo "$fNew<br>";
} else if (strpos($following1, "$user3, ")) {
$use3 = "$user3, ";
$fNew = str_replace("$user3", "", $following1);
echo "$fNew<br>";
}
} else if ($following1 == $user3) {
echo "Can remove follow.";
$fNew = str_replace($user3, "", $following1);
echo "$fNew<br>";
} else {
echo "Can't remove follow";
}
?>
Have a look a this:
<?php
$follow = "Peter, Franz, Spongebob";
$guyToUnfollow = 'Franz';
$people = explode(',', $follow);
var_dump($people);
foreach ($people as $key => $person) {
$person = trim($person);
if ($person == $guyToUnfollow) {
unset($people[$key]);
}
}
$follow = implode(',',$people);
var_dump($follow);
Firstly, we convert the CSV to an array, then loop through it. We use trim to remove whitespace, and unset any value in the array that matches the guy you want to unfollow. Finally, we recreate the csv using implode.
See it working here https://3v4l.org/QEnHj
strpos returns the position of the string, so you need to check if its not false in stead of checking if its true.
So you should use:
strpos($following1, $user3) !== false
Related
I've written a script that checks bulk input of names received via a textarea and omits all values that are already in the database. It works if you enter just one repeated name. If you enter two or more, it will filter out the first repeated name, treat the rest as unique names and insert them in the database. I can't figure out why.
Firstly, this is an array that is built in another part of the script. It's generated from a database query:
Array
(
[0] => john
[1] => peter
[2] => max
[3] => jake
)
This array is referred to as $onlyHandles. Then this is the script:
if((isset($_POST['extract']) && !empty($_POST['extract']))){
$handles = trim($_POST['extract']);
$handles = explode("\n", $handles);
if(count($handles)>200){
echo 'error';
exit(1);
}
foreach($handles as $handle) {
$handleRep = strtolower(str_replace('#','',$handle));
$handleClean = str_replace(str_split('\\/:*?&"<>=+-#%$|'), ' ', $handleRep, $count);
if ($count > 0) {
echo 'error';
exit(1);
}
else{
if (in_array($handleClean, $onlyHandles)){
$delmessage .= "<p>".$handleClean." is already in your list.</p>";
}
else{
$sqlIns = "INSERT INTO...blah blah blah)";
$resultIns = mysql_query($sqlIns);
$resInsArr[] = array($resultIns);
}
}
}
$countresIns = count($resInsArr);
if ($countresIns > 0){
$delmessage .= "<p>User(s) added to list succesfully!</p>" ;
}
}
Now, if you enter "john" in the textarea, it will shout that the name already exists. If you enter "john" and "max" it will omit john and add max.
Any help would be greatly appreciated.
P.S. regarding the query format, I know, I know, thanks!
I would like to give U some idea about how to achieve it:
Replace the first line:
if((isset($_POST['extract']) && !empty($_POST['extract']))){
through
if((!empty($_POST['extract']))){
because !empty already guives U the guaranty that it isset
I am suspescting some special chars in play
U could also use the power of Regular Expression to replace the unneeded chars
in replacing:
Line 12: $handleClean = str_replace(str_split('\\/:*?&"<>=+-#%$|'), ' ', $handleRep, $count);
Through:
$handleClean = preg_replace("/\[\/:\*?&\"<>=\+-#%\$\|\]*/", ' ', $handleRep, $count);
In Ur For-Loop, what about refactoring the following lines:
line 2: $handles = trim($_POST['extract']);
through (trim is not necessary hier)
$handles = $_POST['extract'];
AND
line 11: $handleRep = strtolower(str_replace('#','',$handle));
through
$handleRep = trim(strtolower(str_replace('#','',$handle)));
Hey ;-),
U should also add some print_r(...) to debug each step
thanks #Ulrich Tevi Horus that made my code a bit cleaner but didn't solve the mysteriously disappearing users.
#shulard, you should post this as an answer to get the upvote. array_diff was indeed the best solution.
Here's the final code. Needs some tidying up but it's good enough to go on my server for testing.
//this is the current contents of the list:
$onlyHandles = array();
foreach ($organizedArray as $key2 => $val2) {
$onlyHandles[] = $val2['name'];
}
echo "<br>begin onlyhandles<br>";
print_r($onlyHandles);
echo "<br>end onlyhandles<br>";
//finish preparation for display
//if names submitted for the list list
if(!empty($_POST['extract'])){
$handles = trim($_POST['extract']);
$handles = explode("\n", $handles); //this is now an array
echo "<br>begin handles<br>";
print_r($handles);
echo "<br>end handles<br>";
//$countInput = count($handles);
if($countInput>200){
echo '<p style="color:red;">Please Enter fewer than 200 names!</p>';
exit(1);
}
else{
$handleFinal = array();
foreach($handles as $handle) {
//$handleRep = strtolower(str_replace('#','',$handle));
$handleRep = trim(strtolower(str_replace('#','',$handle)));
$handleClean = str_replace(str_split('\\/:*?&"<>=+ -#%$|'), 'p', $handleRep, $count);
//$handleClean = preg_replace("/\[\/:\*?&\"<>=\+-#%\$\|\s+\]*/", ' ', $handleRep, $count);
echo "handleClean: ".$handleClean."<br>";
if ($count > 0) {
echo '<p style="color:red;">Your input contained special characters.</p>';
exit(1);
}
else{
$handleFinal[] = $handleClean;
}
}//end foreach
}//finish checking count input number
echo "<br>begin handleFinal<br>";
print_r($handleFinal);
echo "<br>end handleFinal<br>";
$countFinal = count($handleFinal);
echo "<br>countfinal is ".$countFinal."<br>";
//check if this user is already in the list
$handleDiffs = array_diff($handleFinal,$onlyHandles);
echo "<br>begin handlediffs<br>";
print_r($handleDiffs);
echo "<br>end handlediffs<br>";
foreach($handleDiffs as $handleDiff) {
$sqlIns = "blah blah blah";
$resultIns = mysql_query($sqlIns);
$resInsArr[] = array($resultIns);
}
$countresIns = count($resInsArr);
if ($countresIns > 0){
$delmessage .= "<p>User(s) added to the list succesfully!</p>" ;
}
}
I post my comment answer as a real answer :)
You must trim your $handle variable too because it's possible to have some spaces around it...
Then about your problem, I don't understand it. Your code seems "clean", maybe you should consider set the strict flag to true see function definition here.
I have a field that stores multiple zip codes.
A query result for the zip codes column may contain several zip codes: 90027,90028,90068
I need an if statement to check if a single zip code is in the result
$zipstring = $rows['pool_zip_codes']);
$zipsql = "SELECT `pool_zip_codes` FROM `cases` WHERE `id` = '{$rowid}' AND `pool_zip_codes` IN ('{$zipstring}') ";
$zipqry = mysql_query($zipsql);
$zipresult = mysql_fetch_row($zipqry);
if (($zipresult[0]) == '90068') {
this zip code is in the list
} else {
not in list
}
};
try this
$zipresult = mysql_fetch_array($zipqry);
if (($zipresult['pool_zip_codes']) == '90068') {
this zip code is in the list
} else {
not in list
}
use in_array()
as
if (in_array($zipresult[0],$zipresult))
{
echo "this zip code is in the list" ;
}
else {
echo "not in list";
}
If I read your question correctly, you want to distinguish between
#####
and
#####,#####,#####...
To do this, just use a regex to check if the field matches 5 digits.
if (preg_match("/^\d{5}$/", $zipresult[0])) {
...
}
Otherwise, as the others are saying, use in_array(). What they're not saying is that you'd have to explode() the string first, to make an array:
$exploded = explode(",", $zipresult[0]);
if (in_array($exploded, "99999")) {
....
}
EDIT per your comment you could use strpos()
$targetcode = "99999";
$found = array();
foreach ($zipresult as $row) {
if (strpos($row['pool_zip_codes'], $targetcode) !== false) {
$found[] = $row;
}
}
or in_array()
$targetcode = "99999";
$found = array();
foreach ($zipresult as $row) {
$exploded = explode(",", $row['pool_zip_codes']);
if (in_array($exploded, $targetcode)) {
$found[] = $row;
}
}
Split the string and use in_array:
if (in_array(explode(',', $zipresult[0]),$zipresult))
{
#this zip code is in the list
}
else {
#not in list
}
Hello so I have exploded a row from my database, I want to find a specific value based on the exploded array.
My row example.
Josh Johnson|Jenny Launcher|Easter Fonter|Eric Bennett
Here is my code:
<?php
$rowexplode = $row['name'];
$a = explode("|",$rowexplode);
if(count($a)>1) {
$explode_results = $rowexplode;
$explode_array = str_replace("|",", ", $explode_results);
echo $explode_array;
}
else {
echo "";
}
?>
This is what it shows
Josh Johnson, Jenny Launcher, Easter Fonter, Eric Bennett
Now I would like it to grab one of those names and display it.
For example. Grab Easter Fonter from the list and echo something like "Easter Fonter was here".
I don't know if it's possible to specify a specific name out of the exploded array.
You can use in_array function to check. Since you already have data in array $a
if(in_array("Easter Fonter", $a))
It helps to know what you've created at each step of the way:
<?php
$rowexplode = $row['name']; // $rowexplode is now a string
$a = explode("|",$rowexplode);
// $a is an array with strings, such as:
// array('Josh Johnson, 'Jenny Launcher', 'Easter Fonter', 'Eric Bennett')
if(count($a)>1) {
$explode_results = $rowexplode;
// $explode_results is now just a copy of $rowexplode, still just a string
$explode_array = str_replace("|",", ", $explode_results);
// This says array, but it isn't. It's just a string with the pipes replaced:
// "Josh Johnson, Jenny Launcher, Easter Fonter, Eric Bennett"
echo $explode_array;
// Output that string
}
So, if you want the values, you could do:
foreach ($a as $name) {
echo "$name was here\n"; // Echo each name one at a time
}
$arr = ["Josh Johnson", "Jenny Launcher", "Easter Fonter", "Eric Bennett"];
foreach($arr as $name) {
if($name == "Easter Fonter") {
echo $name + " was here";
}
}
This may helpful
//your text here
$rowexplode = 'Josh Johnson|Jenny Launcher|Easter Fonter|Eric Bennett';
$a = explode("|",$rowexplode);
if(count($a)>1) {
//your search string
$name = "Easter Fonter";
//check here
if(in_array($name,$a))
{
echo $name." was here.";
}else{
echo "Name Not Found".implode(', ', $a);
}
}
else {
echo "";
}
?>
I wanted to check to enter data into the database.Checks are as follows
$implode1 = "apple, orange, banana";
$implode2 = "banana, mango";
If the banana in the variable $implode1 is also contained in the variable $implode2, it should display a warning message.
and if the value of the variable is empty, then the execution will be ignored. example:
$implode1 = "";
$implode2 = "";
How to code for the above problem?
Help me please :(
$implode1 = "apple, orange, banana";
$implode2 = "banana, mango";
$implode1Array = explode(", ", $implode1);
$implode2Array = explode(", ", $implode2);
$result = array_intersect($implode1Array, $implode2Array);
if(count($result) > 0) {
exit('Error!');
}
Typically I would assume that by cat you mean concatenation, but it doesn't seem proper here. But, assuming that is what you mean, you would just check for the same concatenation character (a comma) in both variables, like so:
if ( stristr($implode1, ",") && stristr($implode2, ",") ) {
// error
} else {
// success, do something
}
However, assuming you mean the same item being entered in both variables, in this case fruit, you can check it this way:
$im1 = explode(",", $implode1);
$im2 = explode(",", $implode2);
foreach($im1 as $i) {
if ( array_search($i, $im2) ) {
// error
} else {
// success, do something
}
}
You could of course just search both strings for a given value, but I don't think that's what you're going for. But assuming it is, here is that code:
$duplicate = "apple"; // the item you are searching for a duplicate of
if ( stristri($implode1, $duplicate) && stristr($implode2, $duplicate) ) {
// error
} else {
// success, do something
}
if (count(array_intersect)) { /* warning */ }
You can use PHP's array_intersect function to get the intersection (see http://php.net/manual/en/function.array-intersect.php):
$arr1 = explode(", ", "apple, orange, banana");
$arr2 = explode(", ", "banana, mango");
$intersection = array_intersect($arr1, $arr2);
if (count($intersection) > 0) {
echo "WARNING: the lists have a non-empty intersection!";
}
I've got a large flat file of usernames and emails in the following format:
"username", "email"
"username", "email"
"username", "email"
etc...
I need to take the email and search for the username, but for some reason it will not return a result. It works if I search opposite.
$string = "user_email#something.com";
$filename = "user_email.txt";
$h = fopen("$filename","r");
$flag=0;
while (!feof ($h)) {
$buffer = fgets($h);
$thisarray = split(",", $buffer);
if ($string == str_replace('"','', $thisarray[1])) {
$i = 1;
$i++;
echo '<td bgcolor="#CCFFCC"><b style="color: maroon">' . str_replace('"','',$thisarray[0]). '</b></td>';
}
Any ideas? Thanks!
As per reko_t's suggestion: Use fgetcsv to read individual lines of csv into arrays, until you find one where the second element matches your search term. The first element then is the username. Something like:
<?php
function find_user($filename, $email) {
$f = fopen($filename, "r");
$result = false;
while ($row = fgetcsv($f)) {
if ($row[1] == $email) {
$result = $row[0];
break;
}
}
fclose($f);
return $result;
}
You may use fgetcsv() directly
$string = "user_email#something.com";
$filename = "user_email.txt";
$h = fopen("$filename","r");
$flag=0;
while (!feof ($h)) {
list($username, $email= fgetcsv($h);
if ($string == $email) { /* do something */ }
}
fgetcsv() (as a nice side effect) also removes the "field enclosures" (the double quotes ") for you, if they exists.
Your own example probably does not work, because if you have such a line
"username", "email"
splitting at , will result in
'"username"'
' "email"'
Notice the whitespace before "email", that you forgot to remove. Additional using str_replace() to remove the surrounding quotes is quite unsafe. Have a look at trim().
First, just use file() to get the contents of the file into an array:
$file_contents = file( $filename, 'r' );
Now loop through the contents of the array, splitting the strings and examining the email address:
foreach ( $file_contents as $line ) {
list ( $username, $email ) = str_split( ',' $line );
if ( trim( $email ) == $string ) {
// A match was found. Take appropriate action.
}
}
I think the easiest solution is to use file() with str_getcsv().
The code would be something like this:
foreach (file($fileName, FILE_SKIP_EMPTY_LINES) as $line) {
$columns = str_getcsv($line); // Where $columns[0] and $columns[1] hold the username and email respectively.
}
I truly believe that all examples in other answers works!
But all they are slow, because all of them travers each line in csv file...
I have another example how to find desired string:
$command = sprintf("grep '%s,%s' -Er %s", $userName, $email, $file);
$result = `$command`;
Yes it some kind of dark matter, but it really works and it really fast!
While fgetcsv is potentially a more elegant solution, that doesn't answer your original question: your second array element has a newline, and you're comparing against a string that doesn't.
To fix:
if ($string == str_replace('"','', chop($thisarray[1]))) {