Search code examples
phpregexstringreplacesubstr

Find the first match for a string in text and return sample of original text


I have a text that includes all sort of special chars and I need to find the first match for a string and then return something like this 10 chars + first match + 10 chars. In other words a sample of the text where the first match is around the middle.

Example:

$text = "+!This is a text with some % special chars/text and ( for a string query to match. Then !! mor&&&e and so on...chars/text.";
$stringToFind = "hars/t";

It should return:

$grabtext = "% special chars/text and ( for";

I made the example of a string to find that is not a complete word and has 1 special char.


Solution

  • From the PHP manual

    strpos — Find the position of the first occurrence of a substring in a string

    So if we use that function to locate the offset of the substring we can easily use something like substr to obtain a substring of 10 characters +/- from that offset.

    function grabText($string, $searchString) {
        if (($x = strpos($string, $searchString)) === false) {
            return; // no match found
        }
        $y = strlen($searchString) + 20;
        $x = max(0, $x - 10);
        return substr($string, $x, $y);
    }
    
    $text = "+!This is a text with some % special chars/text and ( for a string query to match. Then !! mor&&&e and so on...chars/text.";
    $stringToFind = "hars/t";
    echo grabText($text, $stringToFind); //  special chars/text and (