Replace part of a string from a specific character

时间:2017-04-10 00:01:43

标签: php replace preg-replace

How would I go about replacing everything from the ? in the following string:

profile_photo.jpg?1491781969

using str_replace in PHP.

So this is removed: ?1491781969

Cheers

3 个答案:

答案 0 :(得分:1)

Use strpos to find the position of the '?' in your string. Then pass that in as the 3rd (length) parameter of substr to get all the characters in the string from 0 through (length).

<?php
$str = 'profile_photo.jpg?1491781969';
echo substr($str, 0, strpos($str, '?'));
?>

答案 1 :(得分:0)

You can remove everything after the ? using explode:

<?php
$string = "profile_photo.jpg?1491781969";
echo explode('?',$string)[0];
?>

答案 2 :(得分:0)

Use preg_replace with mask /?\d+/ instead.
str_replace does not look for patterns and you must specify the exact string value.