I am trying to come up with a general expression which would return the string "logo = ..." for example in this case "logo = Yahoo! logo.svg" but would like it to return the complete string from the "l" in logo until the "|". Currently I'm getting and error: Notice: Undefined offset: 0 when clicking submit. Please see script below:
<html>
<body>
<h2>Search</h2>
<form method="post">
Search: <input type="text" name="q" value="Yahoo!"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$url_2 = "http://en.wikipedia.org/w/api.php?
action=query&prop=revisions&rvprop=content&format=json&titles=$search&rvsection=0&continue=";
$res_2 = file_get_contents($url_2);
$data_2 = json_decode($res_2);
?>
<h2>Search results for '<?php echo $search; ?>'</h2>
<ol>
<?php foreach ($data_2->query->pages as $r):
?>
<li>
<?php foreach($r->revisions[0] as $a);
echo $a;
print_r(preg_match_all('/ logo += (.*)/', $a, $result, PREG_PATTERN_ORDER));
echo trim($result[0][0]);
?>
</li>
<?php endforeach; ?>
</ol>
<?php
}
?>
</body>
</html>
print_r(preg_match_all('/ logo += (.*)/', $a, $result, PREG_PATTERN_ORDER));
echo trim($result[0][0]);
There are two errors in this sample of code. First there is a space before "logo" in the pattern. Your test string doesn't seem to have this space.
Second, when you use preg_match
or preg_match_all
and want to use the match result, you need to use an if statement (because if the pattern is not found, indexes of $result
are not set):
if (preg_match_all('/logo += (.*)/', $a, $result)) {
echo trim($result[0][0]);
} else {
echo 'Not found';
}
Note too that PREG_PATTERN_ORDER
is the default value of the 4th parameter of preg_match_all