views:

95

answers:

1

I need to do a preg_replace for the exact opposite of this preg_match regular expression:

preg_match('#^(\w+/){0,2}\w+\.\w+$#', $string);

So I need to replace all strings that are not valid with an empty string -> ''

So it needs to remove the first / and last / if found, and all non-valid characters, that is the only valid characters are A-Z, a-z, 0-9, _, ., and / (if it's not the first or last characters of the string).

How can I accomplish this with the preg_replace?

Thanks :)

A: 
preg_replace('#^/|/$|[^A-Za-z0-9_./]#D', '', $subject);
Matthew Flaschen
Is that `A-z` supposed to be `A-Z`? Just wondering and thanks :)
SoLoGHoST
Yes, it was a typo. The D addresses an edge case where the string ends with /\n (slash then newline). This / is deleted without the D and allowed with it. It stands for PCRE_DOLLAR_ENDONLY (http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php)
Matthew Flaschen
Ok, I can't have a / at the end of the string, so I wouldn't use this `D` right? Thanks again.
SoLoGHoST
With or without the D, a `/` at the very end is deleted. Without the D, a string ending in /\n also has the / deleted.
Matthew Flaschen
I am grabbing this from an XML document, for example: `<path>/apath/anotherPath/</path>` So it needs to remove the 2 slashes, 1 at the beginning and 1 at the end. Would I need the `D` for this?
SoLoGHoST
Ok, thanks, so I don't need the D than. Thanks a lot :)
SoLoGHoST
Also, can you tell me, how I can add `-` as a valid character if found before the `.` within this PCRE: `preg_match('#^(\w+/){0,2}\w+\.\w+$#', $string)` Thank You...
SoLoGHoST
@SoLoGHoST, If I understand right, `'#^([\w-]+/){0,2}[\w-]+\.\w+$#'`
Matthew Flaschen
Thank You Very Much :)
SoLoGHoST