tags:

views:

75

answers:

7

My value is stored within a string inside (). I need to return this value to check if it's empty.

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

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

This code would be used to show links with no posts in them in Wordpress.

A: 

Your question doesn't quite make sense - although you should look at using instr

Shane
Or strpos and its variants.
Tegeril
A: 

You can use preg_match to extract the value from your string. But if you just need to know whether the value is empty, checking whether your string contains () should work just as well.

Wim
A: 

Are you looking for a string's value, or just check to see if it is empty?

If your checking if the string is empty try

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

to return the string

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

This:

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

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

Would output (testing). Hopefully that is what you were looking for :o)

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

$value = $matches[1];
echo $value;
Mark Baker
Thanks Artefacto
Mark Baker
A: 

Putting all of this together, it is clear from the example that InnateDev intends to test against positive numeric values inside the parentheses. In my opinion, the safest way to do this would be:

$testString = "<a href=\"http://www.link-url.ext\"&gt;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
}  

Note A: Maybe this is redundant, in which case you're free to ignore it - this can also go as a comment to Mark Baker's answer (sorry, don't have those 50 rep yet :( ) - if you're working in an environment where error_reporting includes E_NOTICE and if the tested string comes from an untrusted source then $matches[1] will raise a notice when no parantheses are present. Just wanted to point this one out.

Denis 'Alpheus' Čahuk