Skip to content

Instantly share code, notes, and snippets.

@jakerb
Last active October 28, 2015 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakerb/ab04e3b96031d292c70d to your computer and use it in GitHub Desktop.
Save jakerb/ab04e3b96031d292c70d to your computer and use it in GitHub Desktop.
A small PHP utility to find within a string based on a start and end point.
<?php
/*
* Small Utility to find within a string based on a start
* and end point.
* https://github.com/jakerb
* http://jakebown.com
* @jakebown1
*/
function str_find($f, $t, $str) {
preg_match_all("#" . $f . "(.*?)" . $t . "#msi", $str, $result);
if (is_array($result)) {
$output = [];
foreach ($result as $r) {
if (is_array($r)) {
foreach ($r as $sr) {
$output[] = $sr;
}
}
else {
$output[] = $r;
}
}
return $output;
}
else {
return false;
}
}
?>
<?php
require "find.php";
$exampleA = "<p>Hello World</p>";
$exampleB = "<a href=\"#\">I'm a Link</a>";
$exampleC = "<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>";
print_r(str_find("<p>", "</p>", $exampleA)); //Get text in tag
/* Array
(
[0] => <p>Hello World</p>
[1] => Hello World
)
*/
print_r(str_find("<a href=\"", "\">", $exampleB)); //Get Link from A
/*
Array
(
[0] => <a href="#">
[1] => #
)
*/
print_r(str_find("<li>", "</li>", $exampleC)); //Get text from lists
/*
Array
(
[0] => <li>Item 1</li>
[1] => <li>Item 2</li>
[2] => <li>Item 3</li>
[3] => Item 1
[4] => Item 2
[5] => Item 3
)
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment