Search code examples
phpstr-replacestrpos

PHP strpos() and str_replace()


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";
}

?>

Solution

  • 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