phphtmlreplaceentities

php replace between strings like „ or „ or „ or „


I like to php replace this String:

This String is called „Foo“ or „Bar“ but could be formatted as „Foo“ or even „Bar“ and many more combinations.

with some kind of BB Code

This String is called [quote=Foo] or [quote=Bar] but could be formatted as [quote=Foo] or even [quote=Bar] and many more combinations.

I try to replace and with „ and “ in php but that wasn't work at all.

I don't even know how to start at all :/

Any help would be appreciated.


Solution

  • Take your input string, normalize the escape sequences by un-encoding them, then a simple RegEx should work.

    
    // Original string
    $s1 = <<<EOD
    This String is called „Foo“ or „Bar“ but could be formatted as &ldquor;Foo&#8220; or even &#8222;Bar&#x0201C; and many more combinations.
    EOD;
    
    // Normalize entities
    $s2 = html_entity_decode($s1, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5);
    
    // Convert to bbCode-like style
    $s3 = preg_replace(
        '/„(.*?)“/',
        '[quote=$1]',
        $s2
        );
    
    print_r($s3);
    

    Demo here: https://3v4l.org/Dfig0