簡體   English   中英

如何使用 preg_match 獲取字符串中的最后一個單詞

[英]How to get the last words in a string with preg_match

我正在嘗試獲取字符串中的最后幾個單詞。 最后一句話,我正在使用這個:

$string = "Hallo dies ist ein extrem langer Text den ich gern gekuerz haette, leider bin ich selbst zu doof dafür und mach hier einen test.";

$pattern = '/[^ ]*$/';

preg_match($pattern, $string, $result);

echo "<br>The last word is:------ ". $result[0] ." ---------<br>";

它工作正常。 但我不參與其中。 最后的樹詞。 我不知道如何更改模式。 感謝您提前提供幫助。

在字符串上使用explode可能會更好,如下所示:

$string = 'Hello, my name is Jordan Doyle';
$string_array = explode(' ', $string);
echo end($string_array);

示例輸出:

root@upstairslinux:~# php example.php
Doyle

root@upstairslinux:~#

這是一個獲取指定數量的線的函數......

<?php
function get_last_words($amount, $string)
{
    $string_array = explode(' ', $string);

    return array_slice($string_array, count($string_array) - $amount);
}

$string = 'Hello, my name is Jordan Doyle';
var_dump(get_last_words(3, $string));

示例輸出:

root@upstairslinux:~# php example.php
array(3) {
  [0]=>
  string(2) "is"
  [1]=>
  string(6) "Jordan"
  [2]=>
  string(5) "Doyle"
}

root@upstairslinux:~#

那將完成這項工作

$pattern = '/(([^ ]*)\s+([^ ]*)\s+([^ ]*))$/';

要么

$pattern = '/((([^ ]*)[\s.]+){3})$/';

編輯

   $patterns = '/\b[a-zA-Z]*\b/';

並使用preg_match_all匹配所有出現的事件

  preg_match_all($patterns, $string, $result);

  $string = "Hallo dies ist ein extrem langer Text den ich gern gekuerz haette, leider bin ich selbst zu doof daf&uuml;r und mach hier einen test.";

 preg_match_all($patterns, $string, $result);

 foreach($result[0] as $value){
  echo "$value ";
 } 



for($length = count($result[0]), $i = 1; $i < 4; $i++){
       $offset = $length - $i;
       echo $result[0][$offset];
     }

上面的片段提取最后3個單詞

在字符串上使用explode可能會更好,如下所示:

<?php 
$cate = 'category-node-25';
$cateId = explode('-', $cate);
echo end($cateId);
?>

輸出 - > 25。

使用 preg_match 查找由標准單詞邊界定義的單詞(而不是僅使用空格)。

if (preg_match('/\w+\s*$/', $string, $matches)) {
    $last_word = $matches[0];
    echo $last_word;
} else {
    echo "No match found";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM