[英]regex replace all occurances of one character?
Lots of topics on this but i can't figure it out, looking for some tips, shouldn't be that difficult. 关于这一点有很多主题,但是我想不通,寻找一些技巧,应该不会那么困难。
I have filename: 我有文件名:
test_file_from_mpc.mp4_snapshot_13.29_[2015.05.13_21.10.11].jpg
i'm trying to use regex to replace the characters _ and then everything starting from snapshot 我正在尝试使用正则表达式替换字符_,然后从快照开始的所有内容
I got snapshot covered, but i can't seem to get how to catch all the occurances of _ to be selected 我得到了快照,但是我似乎无法了解如何捕获要选择的_的所有情况
(_)(snapshot)(.*)
selects only 1 _ 仅选择1 _
I read that . 我读过。 should select "any single character" not sure how to use this properly or if it is what i am looking for. 应该选择“任何单个字符”,不确定如何正确使用它,或者这是否是我在寻找的东西。
Any guidance would be great! 任何指导都会很棒! (this is probably 100% a dupe but i have checked all the suggested threads without finding the solution to this seemingly easy problem!) (这可能是100%的欺骗,但是我已经检查了所有建议的线程,而没有找到针对此看似简单的问题的解决方案!)
Can't comment yet, but for regex to match more than one occurrence, you need the g - global modifier. 尚无法评论,但要使正则表达式匹配多个匹配项,您需要使用g-全局修饰符。
/(_snapshot.*$|_|\.)/gi
https://regex101.com/r/aI7fF8/2 https://regex101.com/r/aI7fF8/2
If you replace purely with space all matching occurences, remember to trim last space. 如果仅用空格替换所有匹配的出现,请记住修剪最后一个空格。
Here's a php sample as well 这也是一个php示例
<?php
$str = "test_file_from_mpc.mp4_snapshot_13.29_[2015.05.13_21.10.11].jpg";
$res = preg_replace(array("/_snapshot.*$/", "/[_.]/"), array("", " "), $str);
print $res; // test file from mpc mp4
snapshot.*$|[_.]
You can try this.Replace by space
.See demo. 您可以尝试此操作。按space
替换。请参见演示。
https://regex101.com/r/mT0iE7/13 https://regex101.com/r/mT0iE7/13
$re = "/snapshot.*$|[_.]/im";
$str = "test_file_from_mpc.mp4_snapshot_13.29_[2015.05.13_21.10.11].jpg";
$subst = " ";
$result = preg_replace($re, $subst, $str);
Another (potentially faster, but not prettier) way would be to use explode() & implode(). 另一种(可能更快,但不是更漂亮)的方法是使用explode()和implode()。
// Split string by underscores
$pieces = explode('_', $filename);
// Get the number of pieces
$n = count($pieces);
// Keep just the file extension in the last piece
$pieces[$n] = substr($pieces[$n], strpos($pieces[$n], '.'));
// Remove the other unwanted pieces
unset($pieces[$n - 1];
unset($pieces[$n - 2];
// Reassemble with spaces instead of underscores
$new_string = implode(' ', $pieces);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.