kate_hudson kate_hudson - 8 months ago 31
PHP Question

Remove specific occurence from string

I have a variable called

that contains the name of a project. In most cases, the name takes the following form

OCT16: Some Project

However, it is not always in this format, sometimes it does not have the month/year prefix.

What I am attempting to do is this. If it does have the prefix MMMYY: then I need to remove this part from the name. Now I know I could probably use something like
to remove this particular pattern from a string, but how do I check that it has this pattern in the first place?

Any advice appreciated.



Use the following approach:

$project_name = 'OCT16: Some Project';
$project_name = preg_replace("/\b[A-Z]{3,4}\d{2}:\s?/u", "", $project_name);

print_r($project_name);  // "Some Project"

// another test case:
$project_name = ' Some Project OCT16: some text';
print_r($project_name);  // "Some Project some text"