亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從右到左提取破折號之間的特定文本

如何從右到左提取破折號之間的特定文本

PHP
阿晨1998 2024-01-19 15:47:00
我的文字看起來像這樣:This is some-text for - Extracted Text - randomThis is-some-text for - Extracted Text - another randomThis-is a third-text for - Extracted Text - more random我想Extracted Text從 PHP 文本中提取。我試過這個。$titleTrimd = explode('-', $title);$TrimdTitle=trim($titleTrimd[1]);我面臨的挑戰是,由于[1]不確定,它選擇了錯誤的文本。我需要從右到左提取才能正常工作(從右側計算破折號的數量)。這樣我總能得到目標文本。這是因為在提取的文本的左側,破折號字符的數量會發生變化,并且可以是任何內容,但右側的數字是靜態的,因此從右到左檢查將起作用。我只是不知道該怎么做。請幫忙。
查看完整描述

1 回答

?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

您可以通過使用來做到這一點explode,然后通過指定從右側開始的位置來提取所需的值:


<?php

function extractText($str)

{

    // Break the string into an array

    $exp = explode('-', $str);


    // `count` will return number of elements in an array.

    // Since array index starts from zero, to retrieve 2nd last element we need to use `-2`

    // Remove spaces at the start and end of the text by using `trim` function

    return trim($exp[count($exp) - 2]); 

}


echo extractText('This is some-text for - Extracted Text - random'); // Extracted Text

echo PHP_EOL;

echo extractText('This is-some-text for - Extracted Text - another random'); // Extracted Text

echo PHP_EOL;

echo extractText('This-is a third-text for - Extracted Text - more random'); // Extracted Text

?>


查看完整回答
反對 回復 2024-01-19
  • 1 回答
  • 0 關注
  • 121 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號