简体   繁体   中英

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 _

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!)

Can't comment yet, but for regex to match more than one occurrence, you need the g - global modifier.

/(_snapshot.*$|_|\.)/gi

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
$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.

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().

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM