У меня есть следующая строка
$text = " Wireless sensor networks (WSNs) enable new applications and
require\r\nnon-conventional paradigms for protocol design due to several
constraints. Owing to the\r\nrequirement for low device complexity together
with low energy consumption (i.e., long\r\nnetwork lifetime), a proper
balance between communication and signal/data processing\r\ncapabilities
must be found. This motivates a huge effort in research activities,
standardization\r\nprocess, and industrial investments on this field since
the last decade.\r\n This survey paper aims\r\nat reporting an overview of
WSNs technologies, main applications and standards, features\r\nin WSNs
design, and evolutions. In particular, some peculiar applications, such as
those\r\nbased on environmental monitoring, are discussed and design
strategies highlighted; a case\r\nstudy based on a real implementation is
also reported. Trends and possible evolutions are\r\ntraced. Emphasis is
given to the IEEE 802.15.4 technology, which enables many applications\r\nof
WSNs. Some example of performance characteristics of 802.15.4-based networks
are\r\nshown and discussed as a function of the size of the WSN and the data
type to be exchanged\r\namong nodes. ";
Я хочу заменить \ r \ n ничем, только если это было продолжено точкой (.); удалить все \ r \ n, но оставить. \ r \ n Я написал следующую функцию:
function ReplaceText($haystack,$needle){
$lastPos = 0;
$positions = array();
$rText = "";
while (($lastPos = strpos($haystack, $needle, $lastPos))!== false)
{
$positions[] = $lastPos;
if (substr($haystack, $lastPos-1, 1) == '.') {
// do nothing
} else {
$rText .= substr($text, 0, $lastPos).str_replace('\r\n', '', substr($text, $lastPos));
}
$lastPos = $lastPos + strlen($needle);
}
return $rText;
}
Это не работает!
str_replace(".\r\n", '', $text)@u_mulder Это удалит даже предыдущую точку.
Может мой вопрос был непонятен. Мне нужно заменить все вхождения \ r \ n, но сохранить. \ R \ n
«Я хочу заменить \ r \ n ничем, но только если это было продолжено точкой (.)» Только если это было продолжено.
Ваш первоначальный вопрос и ваш последний комментарий на 100% противоречат друг другу.
извините ishegg, я заметил это сейчас и исправил. извините за путаницу.
Это означает «удалить \ r \ n, если ему предшествует нет».
@u_mulder Вы правы, я неправильно понял вопрос.






Вот рабочий пример, из которого вы можете поучиться ...
<?php
// The haystack
$haystack1 = " Wireless sensor networks (WSNs) enable new applications and
require\r\nnon-conventional paradigms for protocol design due to several
constraints. Owing to the\r\nrequirement for low device complexity together
with low energy consumption (i.e., long\r\nnetwork lifetime), a proper
balance between communication and signal/data processing\r\ncapabilities
must be found. This motivates a huge effort in research activities,
standardization\r\nprocess, and industrial investments on this field since
the last decade.\r\n This survey paper aims\r\nat reporting an overview of
WSNs technologies, main applications and standards, features\r\nin WSNs
design, and evolutions. In particular, some peculiar applications, such as
those\r\nbased on environmental monitoring, are discussed and design
strategies highlighted; a case\r\nstudy based on a real implementation is
also reported. Trends and possible evolutions are\r\ntraced. Emphasis is
given to the IEEE 802.15.4 technology, which enables many applications\r\nof
WSNs. Some example of performance characteristics of 802.15.4-based networks
are\r\nshown and discussed as a function of the size of the WSN and the data
type to be exchanged\r\namong nodes. ";
// The first needle
$needle1 = ".\r\n";
// The second needle
$needle2 = "\r\n";
// First we find all occurrances of .\r\n and replace it with a ramdom_text_of_your_choice.
$results1 = ReplaceText1($haystack1,$needle1);
// We are now free to remove only the \r\n instances...
$results2 = ReplaceText2($haystack1,$needle2);
// Finally we change ramdom_text_of_your_choice back to .\r\n
$results3 = ReplaceText3($haystack1,$needle1);
echo $results3;
// The function
function ReplaceText1($haystack1,$needle1){
return str_replace($needle1, 'ramdom_text_of_your_choice', $haystack1);
}
// The function
function ReplaceText2($haystack1,$needle2){
return str_replace($needle2, '', $haystack1);
}
// The function
function ReplaceText3($haystack1,$needle1){
return str_replace($needle1, '.\r\n', $haystack1);
}
?>
Поскольку str_replace заменяет символы слева направо, вы можете использовать это хитрое решение:
echo str_replace([".\r\n", "\r\n", '__xyz__'],['__xyz__', '', ".\r\n"],$text);
// first replace `.\r\n` with some unique list sequence `__xyz__`
// then replace the remaining `\r\n`
// then replace unique list sequence `__xyz__` back with `.\r\n`
Решение Regexp находится здесь:
echo preg_replace("/([^\.])\r\n/", '$1', $text);
я думаю, это быстрое решение. но если в абзаце есть слова __xyz__, это приведет к непредвиденному результату. но я думаю, что __xyz__ должен быть в порядке
@AZakaria ну ... вы можете проголосовать за это как за принятый ответ, если этот ответ поможет вам решить вашу проблему
Невероятно умно. Ух ты.
Я пытаюсь проголосовать, но он говорит, что не могу, так как моя репутация меньше 15! как можно поднять мою репутацию ?!
@AZakaria Но можно прими этот ответ :)
Вы можете использовать отрицательный просмотр назад в регулярном выражении:
$text = preg_replace('~(?<!\.)\r\n~', ' ', $text);
Пример :
$text = "foo\r\nbar.\r\ntest";
$text = preg_replace('~(?<!\.)\r\n~', ' ', $text);
echo $text; // "foo bar.\r\ntest"
И под «не работает» вы имеете в виду?