Вырежьте большое предложение по PHP - PullRequest
0 голосов
/ 02 марта 2012
$string = '"Above all," said British Prime Minister David Cameron, "what I think matters is building the evidence and the picture so we hold this criminal regime to account, and to make sure it is held to account for crimes that it is committing against its people." He spoke to reporters outside a meeting of leaders of the European Union in Brussels, Belgium.';

Как мне обрезать эту строку до указанного количества слов? Например, 5 или 10.

И удалить такие символы, как "&*$%>. Некоторая функция в php?

Должно работать и для неанглийских языков.

Ответы [ 6 ]

3 голосов
/ 02 марта 2012

Попробуйте это:

// The number of words you want to keep
$numwords = 5;

// The symbols you want to have removed
$stripChars = array('"', '&', '*', '$', '%', '>');

$string = '"Above all," said British Prime Minister David Cameron, "what I think matters is building the evidence and the picture so we hold this criminal regime to account, and to make sure it is held to account for crimes that it is committing against its people." He spoke to reporters outside a meeting of leaders of the European Union in Brussels, Belgium.';

$string = str_replace($stripChars, '', $string);

$stringImpl = array_slice(explode(' ', $string, $numwords + 1), 0, $numwords);
$stringCleaned = implode(' ', $stringImpl);
2 голосов
/ 02 марта 2012

Вы можете попробовать что-то вроде этого. Не проверено и может быть немного повозится, но это дает вам представление.

$num_words = 5;
$string = '"Above all," said British Prime Minister David Cameron, "what I think matters is building the evidence and the picture so we hold this criminal regime to account, and to make sure it is held to account for crimes that it is committing against its people." He spoke to reporters outside a meeting of leaders of the European Union in Brussels, Belgium.';
$string = preg_replace('/["&*$%>]/i', '', $string);
$words = explode(" ", $string);
$newstring = implode(" ", array_slice($words, 0, $num_words));
1 голос
/ 02 марта 2012

Если вы хотите добавить т. Е. Тег <br/> между нужным количеством слов, вы можете использовать функцию, вот пример (однако меня не устраивает название функции)

function join_string($str, $word_count=5, $delimiter='<br/>') {
    $words = preg_split('/\s/',preg_replace('/["&*$%>]/','',$str));
    // splits each word
    $str = '';
    foreach ($words as $key => $value) {
        $i = $key % $word_count;
        if ($key > 0 && !$i) $str .= $delimiter;
        // adds the delimiter
        $str .= $value . ($i < $word_count-1 ? ' ' : '');
        // adds the space after the word
    }
    return $str;
}

echo join_string($string,5);
1 голос
/ 02 марта 2012

Используйте эту функцию, чтобы разбить строку на количество слов:

function substrwords($str, $n) {
    $words = explode(' ',$str);
    $outstr = '';
    for($i=0;$i<$n;$i++){
        $outstr .= $words[$i].' ';
    }
    return ltrim($outstr);
}
1 голос
/ 02 марта 2012

Чтобы удалить указанные символы, вы можете сделать что-то вроде этого:

$patterns = array();
$patterns[0] = '/&/';
$patterns[1] = '/%/';
$patterns[2] = '/>/';
preg_replace($patterns, '', $string);

Просто добавьте больше элементов в массив, если хотите удалить больше.

Чтобы вырезать строку, сделайте это. Остерегайтесь, вы можете получить длинный вывод, если вы используете такие слова, как supercalifragilisticexpialidocious:

$newlen = 5; // change accordingly.
$stringarray = explode(' ', $string); // Explodes the string into an array. One item for each row.
$string = implode(' ', array_slice($stringarray, 0, $newlen)); // We then 'slice' the array, which basically cuts it. The 0 defines the starting point and the $newlen the end. After this we 'implode' it which basically converts it to a string. The ' ' shows what we want to stick in-between the items in the array.
0 голосов
/ 02 марта 2012

Вы должны использовать substr

$string = '"Above all," said British Prime Minister David Cameron, "what I think matters is building the evidence and the picture so we hold this criminal regime to account, and to make sure it is held to account for crimes that it is committing against its people." He spoke to reporters outside a meeting of leaders of the European Union in Brussels, Belgium.';

//specify the number after which the string should be cut
$string_cut_position = 5;

$new_string = substr($string, 0, $string_cut_position);

Чтобы удалить специальный символ, например: "&*$%>

$new_string = preg_replace('/["&*$%>]/i', '', $new_string);

Если вы хотите удалить все не алфавитно-цифровые символы, вы можете использовать

$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $new_string );

Надеюсь, это поможет:)

РЕДАКТИРОВАТЬ:

Извините, неправильно прочитал вопрос. я думал о сокращении букв: (

Вы можете попробовать

//specify the number after which the string should be cut
$words_cut_position = 5;

$new_string = array_slice(explode(' ', $string, $words_cut_position + 1), 0, $words_cut_position);
$output_string  = implode(' ', $new_string);

Надеюсь, это поможет:) ..

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...