简体   繁体   中英

PHP regular expression not working with string from database

preg_replace does not return desired result when I use it on string fetched from database.

$result = DB::connection("connection")->select("my query");
foreach($result as $row){

    //prints run-d.m.c.
    print($row->artist . "\n");

    //should print run.d.m.c
    //prints run-d.m.c
    print(preg_replace("/-/", ".", $row->artist) . "\n");
}

This occurs only when i try to replace - (dash). I can replace any other character. However if I try this regex on simple string it works as expected:

$str = "run-d.m.c";

//prints run.d.m.c
print(preg_replace("/-/", ".", $str) . "\n");

What am I missing here?

It turns out you have Unicode dashes in your strings. To match all Unicode dashes, use

/[\p{Pd}\xAD]/u

See the regex demo

The \\p{Pd} matches any hyphen in the Unicode Character Category 'Punctuation, Dash' but a soft hyphen, \\xAD , hence it should be combined with \\p{Pd} in a character class.

The /u modifier makes the pattern Unicode aware and makes the regex engine treat the input string as Unicode code point sequence, not a byte sequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM