함수 str replace nth()

Jmnote bot (토론 | 기여)님의 2020년 11월 2일 (월) 02:36 판 (봇: 자동으로 텍스트 교체 (-source +syntaxhighlight))
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)


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 }}