Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do store a portion of a string as a variable? 2

Status
Not open for further replies.

farley99

MIS
Joined
Feb 12, 2003
Messages
413
Location
US
I want to extract the number between <b> and </b> from this string, in this case 5
<a href=&quot;hello.php&quot; class=&quot;links&quot;><b>5</b><br>Visitors</a>

grep(<a href=&quot;hello.php&quot; class=&quot;links&quot;><b>([0-9]+)</b><br>Visitors</a>);
$number=$1;

What is the correct syntax?
 
No, that syntax is not correct. PHP doesn't have a builtin function grep().

You might try preg_replace() (
Code:
<?php
$a = '<a href=&quot;hello.php&quot; class=&quot;links&quot;><b>5</b><br>Visitors</a>';

$foo = preg_replace ('/.*<a href=&quot;hello.php&quot; class=&quot;links&quot;><b>([0-9]+)<\/b><br>Visitors<\/a>.*/', '$1', $a);

With the preg_*() functions, you must escape the slashes in HTML closing tags (&quot;<\/a>&quot;) in your search pattern.
print $foo;
?>

Want the best answers? Ask the best questions: TANSTAAFL!!
 
Alternative solution:
Code:
$number = intval(strip_tags($string));
This would work in your case since the digit is the first thing to apear in the stripped version.
There are more possibilities like this, however, the regular expression should be your choice. I'd only recommend to make it more abstract because you lock yourself in specifying the anchor tag with the attributes. If anything changes in there, like the CSS class, you need to adjust the expression.
There would be probably also other ways to get the value. The only question is:
How did it get there?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top