Anonymous992 Anonymous992 - 1 year ago 99
PHP Question

Concatenate regex

I am trying to get this all into one query, but my regex skills are not so grand. I did get it to work in this ungraceful manner. Any assistance is greatly appreciated.

the source $url would look like this:


the end result I need looks like this:


This is what could use some efficiency

$urlName1 = preg_replace("/[0-9]/","",$url);
$urlName2 = preg_replace("/(o)/","",$urlName1);
$urlName = preg_replace("/(\/)/","",$urlName2);

Answer Source

Just include the other characters in your character class for replacement.

$url = "/o/33484/bob-nomai";
echo preg_replace("~^/o[0-9/]+~", "", $url); // bob-nomai

There's no way you're doing preg_replace("/(o)/", "", $urlName1) because that would just result in getting the string "bb-nmai", which clearly isn't what you want.

Instead, you seem to want to remove the leading "/o" at the begging of the string, which can be achieved in PCRE with an anchor.

Outside a character class, in the default matching mode, the circumflex character (^) is an assertion which is true only if the current matching point is at the start of the subject string.

So ^/o will match the /o at the beginning of the subject and any proceeding characters of [0-9/].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download