1

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?

6
  • If you use '/\p{Pd}/' pattern, do you match the hyphen/dash? Commented Oct 17, 2016 at 8:13
  • no, still prints same string Commented Oct 17, 2016 at 8:16
  • Then, there might be just no - in the string. Not sure if it might help, try also adding /u modifier, /\p{Pd}/u. Commented Oct 17, 2016 at 8:17
  • Can you show the exact output? Commented Oct 17, 2016 at 8:19
  • It's likely that what looks like a dash is in reality a minus sign or another kind of dash (which may be different characters). Commented Oct 17, 2016 at 8:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.