0

This should be obvious, but I'm having trouble.

I want to replace several characters (dashes, spaces, underscores) with an empty string, but I've got something wrong.

This code: $tmp = preg_replace('/[ -_]/', '', 'filename-1055');

...returns this: "filename"

...when I'm expecting this: "filename1055"

Why the truncation?

4 Answers 4

2

Try str_replace instead:

$tmp = str_replace(array("-", "_", " "), "", 'filename-1055');

Unless there is a particular reason you are using preg_replace.

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

2 Comments

Actually, str_replace(array("-", "_", " "), "", $string); would meet OPs requirements better. "I want to replace several characters (dashes, spaces, underscores) with an empty string"
You're welcome. For this scenario, str_replace is much less overhead for a simple task than preg_replace. +1.
1

In a character class, dash - is the range operator, so your class [ -_] means any character in the range (space) to _.

You have two possibilities:

1- move the dash in the first or last position in the character class: [- _] or [ _-]
2- or escape it: [ \-_]

Comments

1

Try this way, DEMO

$re = "/([-\\s_])/"; 
$str = "filename-1055\n"; 
$subst = ""; 

$result = preg_replace($re, $subst, $str, 1);

Comments

0

Its because you did not escape - (range operator inside []) with \-. Correct code would be:

$tmp = preg_replace('/[ \-_]/', '', 'filename-1055');

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.