함수 str replace nth()


1 Bash[ | ]

  • (주의) 1-based
str='hello world hello my friend hello hi'
echo $str | sed 's/hello/yellow/1'
# yellow world hello my friend hello hi
echo $str | sed 's/hello/yellow/2'
# hello world yellow my friend hello hi

2 PHP[ | ]

function str_replace_nth($search, $replace, $subject, $nth) {
	$found = preg_match_all('/'.preg_quote($search).'/', $subject, $matches, PREG_OFFSET_CAPTURE);
	if( $found === false || $found <= $nth ) return $subject;
	return substr_replace($subject, $replace, $matches[0][$nth][1], strlen($search));
}
$str = 'hello world hello my friend hello hi';
echo str_replace_nth('hello', 'yellow', $str, 0);
echo str_replace_nth('hello', 'yellow', $str, 1);
echo str_replace_nth('hello', 'yellow', $str, 2);
echo str_replace_nth('hello', 'yellow', $str, 3);
# yellow world hello my friend hello hi
# hello world yellow my friend hello hi
# hello world hello my friend yellow hi
# hello world hello my friend hello hi

3 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}