替换子字符串直到 space 在 PHP 中的指定位置之后找到

Replace substring till space is found after specified position in PHP

我有这个主串

$string = "This is a sample text";
$substring = substr_replace($string, "", 11 , 6);

输出:

This is a text

我正在将 $string 变量传递给 substr_replace 函数,从 11 索引到 6 索引,即 sample 将被替换为空白字符串,但我不想硬-code 6...我想替换字符,直到在指定的偏移量之后找到第一个 space。

解决此问题的任何解决方案。谢谢

可以用strpos带偏移量找到第一个spaceat/after指定位置的位置;然后使用 substr_replace 删除子字符串:

$tests = [
    "This is a sample text",
    "This is a dummy text",
    "This is a test text"
];
foreach($tests as $test) {
    $start_pos = 10;
    $space_pos = strpos($test, " ", $start_pos);
    assert($space_pos !== false);
    $result = substr_replace($test, "", $start_pos, $space_pos - $start_pos + 1);
    echo $test . " -> " . $result . PHP_EOL;
}

# This is a sample text -> This is a text
# This is a dummy text -> This is a text
# This is a test text -> This is a text
function niceCut($str, $cut) {
    $ns = '';
    for ($i = 0; $i < strlen($str); $i++) {
        $ns .= $str[$i];
        if ($i > $cut && ($str[$i] === " ")) {
            return $ns; 
        } 
        
    }
    return $ns;
}


echo '<p>'. niceCut( "Hello World and hello Text" , 3 ) . '</p>'; // Hello
echo '<p>'. niceCut( "Hello World and hello Text" , 5 ) . '</p>'; // Hello World

我肯定会用正则表达式来做到这一点。我从你的问题中推断出你想删除句子中的第 4 个单词。同时,如果您想要的是保留前 10 个字符并删除下一个 space 之前的任何内容,这仍然是可能的。以下示例演示了 2 种可能性:

<?php
$tests[] = "This is a sample text";
$tests[] = "This is a sample text which can get longer";
$tests[] = "A random sentence ausage we can cleanup";

$word_based_regex = '/^((\w* ){3})(\w* )(.*)$/';
$position_based_regex = '/^(.{10})(\w* )(.*)$/';

foreach ($tests as $sentence) {
    echo "original sentence: $sentence" . PHP_EOL;
    echo "replace with word regex: " . preg_replace($word_based_regex, '', $sentence) . PHP_EOL;
    echo "replace with position regex: " . preg_replace($position_based_regex, '', $sentence) . PHP_EOL;
    echo PHP_EOL;
}

给出:

$ php test_file.php
original sentence: This is a sample text
replace with word regex: This is a text
replace with position regex: This is a text

original sentence: This is a sample text which can get longer
replace with word regex: This is a text which can get longer
replace with position regex: This is a text which can get longer

original sentence: A random sentence ausage we can cleanup
replace with word regex: A random sentence we can cleanup
replace with position regex: A random sausage we can cleanup