簡體   English   中英

從字符串中檢索單詞

[英]Retrieve word from string

我有以下代碼:

$getClass = $params->get('pageclass_sfx');
var_dump($getClass); die();

上面的代碼返回以下內容:

string(24) "sl-articulo sl-categoria"

如何在不影響其位置的情況下檢索想要的特定單詞?

我見過人們為此使用數組,但這取決於您輸入這些字符串的位置(我認為),並且這些位置可能會有所不同。

例如:

$myvalue = $params->get('pageclass_sfx');
$arr = explode(' ',trim($myvalue));
echo $arr[0];

$arr[0]將返回:sl-articulo

$arr[1]將返回:sl-categoria

謝謝。

您可以將substr與strpos結合使用:

http://nl1.php.net/substr

http://nl1.php.net/strpos

$word = 'sl-categoria';
$page_class_sfx = $params->get('page_class_sfx');      
if (false !== ($pos = strpos($page_class_sfx, $word))) {
    // stupid because you already have the word... But this is what you request if I understand correctly
    echo 'found: ' . substr($page_class_sfx, $pos, strlen($word)); 
}

如果您已經知道單詞,就不確定是否要從字符串中獲取單詞。您想知道它是否在那里? false !== strpos($page_class_sfx, $word)就足夠了。

如果您確切知道要查找的字符串,那么stripos()應該就足夠了(如果需要區分大小寫,也可以使用strpos() )。 例如:

$myvalue = $params->get('pageclass_sfx');

$pos = stripos($myvalue, "sl-articulo");
if ($pos === FALSE) {
    // string "sl-articulo" was not found
} else {
    // string "sl-articulo" was found at character position $pos
}

如果需要檢查字符串中是否有某些單詞,可以使用preg_match函數。

if (preg_match('/some-word/', 'many some-words')) {
    echo 'some-word';
}

但是此解決方案可用於一小部分所需的單詞。

對於其他情況,我建議您使用其中一些。

$myvalue = $params->get('pageclass_sfx');
$arr = explode(' ',trim($myvalue));
$result = array();
foreach($arr as $key=> $value) {
    // This will calculates all data in string.
    if (!isset($result[$value])) {
        $result[$value] = array(); // or 0 if you don`t need to use positions
    }
    $result[$value][] = $key; // For all positions
    // $result[$value] ++; // For count of this word in string
}

// You can just test some words like follow:
if (isset($result['sl-categoria'])) {
    var_dump($result['sl-categoria']);
}

暫無
暫無

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

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