-3

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;
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
Guru
  • 410
  • 1
  • 7
  • 17

2 Answers2

1

You could do this with a regex, perhaps something like this?

$output = preg_replace('/[^ ]+.png/', '$1','Hi, this is the sample.png');
$output2 = preg_replace('/[^ ]+.jpg/', '$1','Hi, this is the sample.jpg');
print_r($output);
print_r($output2);
mituw16
  • 5,126
  • 3
  • 23
  • 48
1

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>]

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105