2010-06-18 31 views
1

我的值存儲在()內的字符串中。我需要返回這個值來檢查它是否爲空。如何在php中找到字符串中的值

$variable = "<a href=\"http://www.link-url.ext\">My Link</a> (55)"; 
$value = "55"; // how do I get the value? 

if($value < 1) { 
    // no link 
} else { 
    // show link 
} 

此代碼將用於顯示在Wordpress中沒有帖子的鏈接。

回答

2
$variable = "My Link (55) plus more text"; 
preg_match('/\((.*?)\)/',$variable,$matches); 

$value = $matches[1]; 
echo $value; 
0

你的問題並沒有完全意義 - 儘管你應該看看使用INSTR

+0

或者strpos及其變體。 – Aaron 2010-06-18 16:08:32

0

您可以使用preg_match提取從您的字符串值。但是,如果您只需要知道該值是否爲空,那麼檢查您的字符串是否包含()應該同樣適用。

0

你正在尋找一個字符串的值,或者只是檢查它是否爲空?

如果你的檢查,如果字符串爲空嘗試

return empty($mystring); 
0
if(strpos($string,')')-strpos($string,'(')==1)){ 
    #empty 
} 

返回字符串

$newstring = substr($string,strpos($string,'('),strpos($string,')')-strpos($string,'(')); 
0

此:

<?php 
$str = "blah blah blah blah blah blah blah (testing)blah blah blah blah blah "; 

echo preg_filter("/.*(\(.*?\)).*/","\\1",$str); 
?> 

將輸出(測試)。但願這就是你要找的人:O)

0

把所有的這一起,是從example明確表示InnateDev打算再次進行測試積極數值括號內。在我看來,這樣做最安全的方法是:

$testString = "<a href=\"http://www.link-url.ext\">My Link</a> (55)"; 
$matches = array(); 

/* Assuming here that they never contain negative values e.g. (-55) */ 
preg_match('/\((\d*?)\)/s', $testString, $matches); 

$hasComments = false; 

if (count($matches) >= 1) // * Note A 
{ 
    $hasComments = $matches[1] > 0; 
} 

if ($hasComments) 
{ 
    // link 
} 
else 
{ 
    // no link 
} 

注答:也許這是多餘的,在這種情況下,你可以自由地忽略它 - 這也可以去爲Mark Baker評論的answer(對不起,還沒有那些50代表:() - 如果你在一個環境中工作error_reporting包括E_NOTICE,如果測試的字符串來自不可信源,然後$matches[1]將提出通知當沒有皮質存在時,只想指出這一點。

相關問題