[英]Replace all the _ except one before last one
I have the following url: 我有以下网址:
http://distilleryimage3_s3_amazonaws_com/8af11cdcf11e286b022000ae90285_7_jpg
I want to replace the _
with .
我想将
_
替换为.
. 。 However, the
_7
at the end should be kept - it is not a dot. 但是,末尾的
_7
应该保留-它不是点。
So, basically it should look like: 因此,基本上它应该看起来像:
http://distilleryimage3.s3.amazonaws.com/8af11cdcf11e286b022000ae90285_7.jpg
If I use str_replace it will replace all the _
but I need to keep that one there. 如果我使用str_replace,它将替换所有的
_
但是我需要将其保留在那里。 How can I do this? 我怎样才能做到这一点?
Use this ( corrected now! ) 使用它(立即更正! )
<?php
$subject = 'http://distilleryimage3_s3_amazonaws_com/8af11cdcf11e286b022000ae90285_7_jpg';
$pattern = '/(_)(?!\d_jpg)/';
var_dump(preg_replace($pattern, '.', $subject));
This outputs 这个输出
http://distilleryimage3.s3.amazonaws.com/8af11cdcf11e286b022000ae90285_7.jpg
You can use this negative lookahead based regex code: 您可以使用以下基于负前瞻的正则表达式代码:
$s='http://distilleryimage3_s3_amazonaws_com/8af11cdcf11e286b022000ae90285_7_jpg';
$repl = preg_replace('/_(?![^_]*_[^_]*$)/', '.', $s);
//=> http://distilleryimage3.s3.amazonaws.com/8af11cdcf11e286b022000ae90285_7.jpg
Here's a solution that doesn't use regex (works for all numbers, so this won't fail if the number is different from 7
; it doesn't have to be a number -- a string works, too): 这是一个不使用正则表达式的解决方案(适用于所有数字,因此,如果数字与
7
不同,这不会失败;它不必一定是数字-字符串也适用):
<?php
$haystack = 'http://distilleryimage3_s3_amazonaws_com/8af11cdcf11e286b022000ae90285_7_jpg';
//replacing all '_' with '.'
$haystack = str_replace('_', '.', $haystack);
//finding second last occurence of '.'
$n = strrpos($haystack, '.', strrpos($haystack, '.') - strlen($haystack) - 1);
//replacing the nth character to '_'
$haystack[$n] = '_';
echo $haystack;
Output: 输出:
http://distilleryimage3.s3.amazonaws.com/8af11cdcf11e286b022000ae90285_7.jpg
The final _ in a string that is not itself. 字符串本身中的最后一个_。
_(?=[^_]+$)
Edit: my assumption is that this question needs specific knowledge of file extensions to answered correctly. 编辑:我的假设是,这个问题需要特定的文件扩展名知识才能正确回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.