テキストの段落から文字列の一部を削除するタスクがあります。コンセプトは以下の通りです。
1)テキストの段落から括弧「(」および「)」内の文字列の部分を削除する必要があります。
2)次に、開始括弧が元の文字列の先頭から30文字を超える場合は、何も削除しないでください。
$sample_string = 'Pete Fountain (born Pierre Dewey LaFontaine, Jr., July 3, 1930), is an American, New Orleans based clarinetist. According to a Belgian radio program ("La troisieme oreille", produced by Marc Danval), his name was originally Pierre de la Fontaine.';
$output_string = 'Pete Fountain, is an American, New Orleans based clarinetist. According to a Belgian radio program ("La troisieme oreille", produced by Marc Danval), his name was originally Pierre de la Fontaine.'
閉じ括弧「)」は文字列の30文字を超えていますが、それでも文字列のセクションを削除する必要があります。
括弧で囲まれたテキストの多くのセットは、30番目の文字で表示できます。
これがあなたの関数です。「文字列(もう少し文字列(もう少し)いくつかのテキスト)」などの別の括弧内の括弧に対しても機能します。
$ distanceは、開き括弧を先頭から離しておく文字数です(この場合は30文字)。
function remove($str, $distance) {
$arr = explode('(', $str);
// if first opening paranthesis is not farther away from distance or if there are no
// parentheses at all, just return the same string
if (strlen($arr[0]) >= $distance || count($arr) === 1) {
return $str;
}
// get the position of first character after the first opening parenthesis
$currentPos = strlen($arr[0])+1;
$open = '(';
$close = ')';
$openCount = 1;
// loop through each character to find the matching closing parenthesis
while ($currentPos < strlen($str)) {
$char = substr($str, $currentPos,1);
// if we find another opening parenthesis, increase the opening parentheses count
if ($char == $open) {
$openCount++;
}
// if we find a closing parenthesis, decrease openening parentheses count
if ($char == $close) {
$openCount--;
}
// when opening parentheses count is zero, that means we found closing parenthesis
// position, so now we can remove the substring between opening and closing
// parentheses, including the opening and closing parentheses, and return the
// result
if ($openCount === 0) {
$parens = substr($str, strlen($arr[0]), $currentPos - strlen($arr[0])+1);
return str_replace($parens, '', $str);
}
$currentPos++;
}
return $str;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加