У меня есть эта основная строка
$string = "This is a sample text";
$substring=substr_replace($string, '', 11 , 6);
Выход:
This is a text
Я передаю переменную $string в функцию substr_replace, с индекса 11 на индекс 6, т.е. sample будет заменен на blank string, но я не хочу передавать 6 здесь, я хочу заменить символы, пока не будет найден первый пробел, только у меня есть смещение.
Любое решение для решения этой проблемы. Спасибо






Вы можете использовать strpos со смещением, чтобы найти позицию первого пробела в/после указанной позиции; затем используйте 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 символов и удалить все последующие до следующего пробела, это все еще возможно. В следующем примере демонстрируются 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, '\1\4', $sentence) . PHP_EOL;
echo "replace with position regex: " . preg_replace($position_based_regex, '\1\3', $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