kate_hudson kate_hudson - 1 month ago 4
PHP Question

Remove specific occurence from string

I have a variable called

$name
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
preg_replace
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.

Thanks

Answer

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"
Comments