phpfunctionvariablessubstrsquare-bracket

Passing var with square bracket into function, like this [1], brackets not recognized PHP 8.2


PHP 8.2: The last 3 hours I am searching for a solution to identify square brackets from a text. In case I place the string text directly in the function, I can identify the square brackets:

    $Start = "[";
    $sHaystack = "This ist a test[2] looking for square brackets";
    echo "Haystack:". $sHaystack . "<br>";
    $position = mb_strpos($sHaystack,$Start);
    echo "Position of  ".$Start." in haystack is: ".$position."<br>";

Works perfectly. It also works well using preg_replace().

But once the string is delivered into the function while doing the function call, it optically appears well when echoing the string, but the square brackets are not recognized neither with substr(), mb_substr(), preg_replace() and nothing else.

Meanwhile trying the same with this brackets "{" or "(" it works perfectly, also when entered while function call.

My reasoning went to the idea that in some manner the square brackets need to be escaped while the string is being sent into the function.

I already tried adding backslashes etc, but it does not work. Has anyone got an idea?

This is the function ($sStart = "[" and $sEnd="]"):

function identifyBrackets($sHaystack,$sStart,$sEnd){

        // in case content is defined here it works. If entered via function call the square brackets are not identified.
    $sHaystack = "This ist a test[2] looking for square brackets";

        //test with preg_replace, if other brackets are delivered it works
    $what = ['~[[]~', '~[]]~'];
    $with = ['{', '}'];
    $sHaystack = preg_replace($what, $with, $sHaystack);

    echo "Haystack:<br> ".$sHaystack."<br>";

    $position = strpos($sHaystack,$sStart);
    echo "Position of  ".$sStart." in haystack is number: ".$position."<br>"; //with call via function no position found.

    return $sHaystack;

And yes, obviously I already searched all resources here on Stack Overflow, but they treat different problems: Capturing text between square brackets after a substring in PHP PHP preg_replace square brackets How to replace any brackets for rounded brackets using Regular Expression?


Solution

  • I think i got the problem, when I runned file_get_contents here, some of the square brackets were html encoded:

    enter image description here

    So i guess you can use this regex to cover both ways, or search for the encoded characters: &#91; and &#93;

    Regex: &#91;|\[ for [

    Regex: &#93;|\] for ]