Search code examples
phpregexpreg-replacestr-replacestrpos

Return string if it contains specific word


I have a string. I want to write a script in PHP for return a string if it has specific characters.

For example: "Hi, this is the sample.png" is a string. Now I want to output as "Hi, this is the".

I.e., if the string contains .jpg, .png, then I need to replace those words from a string.

This is my sample code:

$output = preg_replace('/.png/', '$1','Hi, this is the sample.png');
print_r($output);exit;

Solution

  • The solution using preg_replace function with a specific regex pattern:

    $str = 'Hi, this is the sample_test.png (or, perhaps, sample_test.jpg)';
    $output = preg_replace('/\b[\w_]+\.(png|jpg)\b/', '', $str);
    
    print_r($output);    // "Hi, this is the  (or, perhaps, )"
    

    If you suppose some other characters to be a part of the "crucial words" - just add them into a character class [\w_ <other characters>]