3

I have a string, a file path, something like

$string = "customer-service/tweep/cs/gsergsergrs/2017-20190Course-Schedule.pdf"

I want to replace all the characters before the backslash with 3 dashes, so that it returns:

$string = ---/---/---/---/2017-20190Course-Schedule.pdf

I have tried using this preg_replace pattern, but it returns ---/2017-20190Course-Schedule.pdf

preg_replace( "/(.+\/)+/", "---/", $string);

Any way to run the replace on every instance of the pattern matching?

Ice76
  • 1,109
  • 8
  • 15

1 Answers1

6

You may use

preg_replace('~[^/]+/~', "---/", $string);
// => ---/---/---/---/2017-20190Course-Schedule.pdf

See the PHP demo.

See the regex demo here. Details:

  • [^/]+ - 1 or more chars other than /
  • / - a forward slash.

Note that / does not have to be escaped since ~ delimiters are used. The preg_replace function replaces all non-overlapping occurrences with the replacement pattern, ---/, so no need using a repeated capturing group (as in the original attempt).

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • 1
    @Ice76 `~` is a [regex delimiter](http://php.net/manual/pl/regexp.reference.delimiters.php). It is not a part of the pattern itself. Read about how patterns are using in PHP [here](http://php.net/manual/pl/reference.pcre.pattern.syntax.php). Then, I can suggest [regexone.com](http://regexone.com/), [regular-expressions.info](http://www.regular-expressions.info), [regex SO tag description](http://stackoverflow.com/tags/regex/info), [What does the regex mean](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). Also, [rexegg.com](http://rexegg.com). – Wiktor Stribiżew Mar 28 '18 at 21:02
  • Will check all those out. Thanks! – Ice76 Mar 28 '18 at 21:05