如何在php中找到字符串中的值

时间:2010-06-18 16:05:00

标签: php string

我的值存储在()内的字符串中。我需要返回此值以检查它是否为空。

$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中没有帖子的链接。

7 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

你的问题没有多大意义 - 尽管你应该考虑使用instr

答案 2 :(得分:0)

您可以使用preg_match从字符串中提取值。但是,如果您只需要知道值是否为空,那么检查字符串是否包含()也应该可以正常工作。

答案 3 :(得分:0)

您是在寻找字符串的值,还是只查看它是否为空?

如果您检查字符串是否为空,请尝试

return empty($mystring);

答案 4 :(得分:0)

if(strpos($string,')')-strpos($string,'(')==1)){
  #empty
}

返回字符串

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

答案 5 :(得分:0)

此:

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

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

输出(测试)。希望这就是你要找的东西:o)

答案 6 :(得分: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
}  

注意A:也许这是多余的,在这种情况下你可以随意忽略它 - 这也可以作为对Mark Bakeranswer的评论(抱歉,还没有那50个代表:() - 如果您在 error_reporting 包含 E_NOTICE 的环境中工作,并且测试的字符串来自不受信任的来源然后$matches[1]会在没有护身符的情况下发出通知。只是想指出这一点。