PHP Find all occurrences of a substring in a string
Without using regex, something like this should work for returning the string positions:
$html = "dddasdfdddasdffff";
$needle = "asdf";
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
// Displays 3 and 10
foreach ($positions as $value) {
echo $value ."<br />";
}
Get string between - Find all occurrences PHP
One possible approach:
function getContents($str, $startDelimiter, $endDelimiter) {
$contents = array();
$startDelimiterLength = strlen($startDelimiter);
$endDelimiterLength = strlen($endDelimiter);
$startFrom = $contentStart = $contentEnd = 0;
while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
$contentStart += $startDelimiterLength;
$contentEnd = strpos($str, $endDelimiter, $contentStart);
if (false === $contentEnd) {
break;
}
$contents[] = substr($str, $contentStart, $contentEnd - $contentStart);
$startFrom = $contentEnd + $endDelimiterLength;
}
return $contents;
}
Usage:
$sample = '<start>One<end>aaa<start>TwoTwo<end>Three<start>Four<end><start>Five<end>';
print_r( getContents($sample, '<start>', '<end>') );
/*
Array
(
[0] => One
[1] => TwoTwo
[2] => Four
[3] => Five
)
*/
Demo.
Get all occurrences of a string between two delimiters in PHP
Just use preg_match_all
and keep things simple:
$input = "|foo| hello |foo| nothing here |foo| world |foo|";
preg_match_all("/\|foo\|\s*(.*?)\s*\|foo\|/", $input, $matches);
print_r($matches[1]);
This prints:
Array
(
[0] => hello
[1] => world
)
How to get a substring between two strings in PHP?
If the strings are different (ie: [foo] & [/foo]), take a look at this post from Justin Cook.
I copy his code below:
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)
Find all text occurrences between h2/h2
Change your Regex to
preg_match_all('#<h2.*?>(.*?)</h2>#i',$text, $found);
Explanation
<h2.*?> - ignore the classes/attributes in the tag if any
(.*?) - capture everything
</h2> - match end tag
i - ignore case
Then Loop through Array and print values
foreach ($found[1] as $a)
echo $a." ";
Get ALL content between two tags in a string
Here is a function I've written some months ago for exactly this issue. You'd have to call the function several times with the offset according to the returned $pos in order to get all accurances. I hope that's acceptable.
/* getSubstring
returns a substring between string_before and string_after,
starts to search at the offset. character of source
returns an array: ['text'] = string found
['pos'] = starting position of string_before within source
returns text = '' and pos = false if string is not found
example: $key = get_substring('12345here67890', '12345','67890')[0];
*/
function getSubstring($source, $string_before, $string_after, $offset = 0, $includeEnvelope = false) {
if (strlen($source)<$offset)
return(array('text' => '', 'pos' => false)); // kind of silly, but prevents an 'Offset not contained in string' warning
$pos1 = strpos($source, $string_before, $offset);
$sb_len = strlen($string_before);
if ($pos1===false) {
$result = '';
}
else {
$pos2 = strpos($source, $string_after, $pos1 + strlen($string_before));
if ($pos2===false) {
$result = '';
$pos1 = false;
}
else {
$result = substr($source, $pos1 + $sb_len, $pos2 - $pos1 - $sb_len);
if ($includeEnvelope)
$result = $string_before.$result.$string_after;
}
}
return (array('text' => $result, 'pos' => $pos1));
}
How to find all substrings between two delimiters in php?
I don't know that explode does the trick, but this seems to:
$string = "var name=cat; *bunch of random strings* var name=dog;*bunch of random strings*var name=cow;*bunch of random strings*";
preg_match_all('/name=([^;]+)/', $string, $matches);
print_r($matches[1]);
or, as a function :
function wizbangStringParser ($string) {
preg_match_all('/name=([^;]+)/', $string, $matches);
return $matches[1];
}
Get content between two strings PHP
- Use
#
instead of/
so you dont have to escape them. - The modifier
s
makes.
and\s
also include newlines. {
and}
has various functionality like from n to m times in{n,m}
.The basic
preg_match('#\\{FINDME\\}(.+)\\{/FINDME\\}#s',$out,$matches);
The advanced for various tags etc (styling is not so nice by the javascript).
$delimiter = '#';
$startTag = '{FINDME}';
$endTag = '{/FINDME}';
$regex = $delimiter . preg_quote($startTag, $delimiter)
. '(.*?)'
. preg_quote($endTag, $delimiter)
. $delimiter
. 's';
preg_match($regex,$out,$matches);
Put this code in a function
- For any file which you do not want to execue any stray php code, you should use file_get_contents. include/require should not even be an option there.
Get multiple matches in string between two strings - small issue in function that I use?
$string = "somerandomcharacters[code]object1[/code]somerandomcharacters[code]object2[/code]somerandomcharacters[code]object3[/code]somerandomcharacters";
preg_match_all('%\[code\](.*?)\[/code\]%i', $string, $matches, PREG_PATTERN_ORDER);
print_r($matches[1]);
Output:
Array
(
[0] => object1
[1] => object2
[2] => object3
)
Regex Explanation:
\[code\](.*?)\[/code\]
Options: Case insensitive
Match the character “[” literally «\[»
Match the character string “code” literally (case insensitive) «code»
Match the character “]” literally «\]»
Match the regex below and capture its match into backreference number 1 «(.*?)»
Match any single character that is NOT a line break character (line feed) «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “[” literally «\[»
Match the character string “/code” literally (case insensitive) «/code»
Match the character “]” literally «\]»
DEMO: http://ideone.com/wVvssx
Related Topics
How to Format an Utc Date to Use the Z (Zulu) Zone Designator in PHP
5.4 Dereferencing to Valid 5.3 Array Call
How to Install Laravel Without Using Composer
JSON_Encode/JSON_Decode - Returns Stdclass Instead of Array in PHP
How to Display All the Images Stored Inside a Database
Only Variables Should Be Passed by Reference In... on Line 13 Fail
How to Manually Return or Throw a Validation Error/Exception in Laravel
Check If Current User Is Administrator in Wordpress
Jquery Tablesorter Index Column Insert
Ajax/PHP - How to Get Posted Data to Load into a Modal on the Same Page
Php: How to Get a List of Classes That Implement Certain Interface
Problems with Lib-Icu Dependency When Installing Symfony 2.3.X via Composer
Transpose Multidimensional Array and Join Values with Commas
Does PHP Run Faster Without Warnings
Fatal Error: Cannot Use Object of Type Stdclass as Array In
How to Retrieve Youtube Video Details from Video Url Using PHP