PHP中的字符串替换

War*_*ior 1 php string

我有字符串命名File_Test_name_1285931677.xml.File是常用词,1285931677是一个随机数.我想删除File__1285931677.xml,即前缀为第一个_,后缀为最后一个_.

Gum*_*mbo 5

你可以这样做explode,array_slice并且implode:

implode('_', array_slice(explode('_', $str), 1, -1))
Run Code Online (Sandbox Code Playgroud)

随着explode字符串被切割成部分,_结果是这样的数组:

array('File', 'Test', 'name', '1285931677.xml')
Run Code Online (Sandbox Code Playgroud)

随着array_slice一切从第二至倒数第二个被抓住了,比如:

array('Test', 'name')
Run Code Online (Sandbox Code Playgroud)

然后使用它将其重新组合在一起implode,从而导致:

Test_name
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用strrpossubstr:

substr($str, 5, strrpos($str, '_')-5)
Run Code Online (Sandbox Code Playgroud)

由于File_有固定长度,我们可以使用5作为起始位置.strrpos($str, '_')返回最后一次出现的位置_.当从该位置减去5时,我们得到从第五个字符到最后一个出现位置的距离,我们将其用作子串的长度.