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)
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.
Extract a substring between two characters in a string PHP
use this code
$input = "[modid=256]";
preg_match('~=(.*?)]~', $input, $output);
echo $output[1]; // 256
working example http://codepad.viper-7.com/0eD2ns
Get string between two strings
You can just explode it:
<?php
$string = 'reply-234-private';
$display = explode('-', $string);
var_dump($display);
// prints array(3) { [0]=> string(5) "reply" [1]=> string(3) "234" [2]=> string(7) "private" }
echo $display[1];
// prints 234
Or, use preg_match
<?php
$string = 'reply-234-private';
if (preg_match('/reply-(.*?)-private/', $string, $display) === 1) {
echo $display[1];
}
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 occurance of string between two strings in php
Refer this link
http://forums.devshed.com/php-development-5/values-string-tags-578670.html
And change your code like this,
preg_match_all("#<abc([^<]+)>#", $yourstring, $ansvariable);
//echo implode("::", $ansvariable[1]);
foreach($yourstring[1] as $key => $val){
echo $yourstring[1][$key]."<br>"; // prints $val
}
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));
}
Get substring between two strings PHP - Reading HTML
I think its because you are declaring text as a local variable inside for loop. so , after when you are assigning $text to fullstring It's actually null. I don't understand what you are trying to do , but do this and see if it works
$fullstring = ""
foreach ($tags as $tag){
#your code as usual
echo($text);
$fullstring = $fullstring.$text;
}
and delete the $fullstring = $text
line.
PHP regex - capturing content between two strings (multiple results)
If there is no section nesting, have a try with
preg_match_all('~\[\[(\w+)]]((?>[^[]+|\[[^[])*)\[\[/\1]]~s', $str, $out)
\[\[(\w+)]]
captures one or more word characters[[
inside]]
In between section-tags used
(?>[^[]+|\[[^[])*
rather than.*?
for better performance but still allowinga[b]c
. If you got nested stuff you can easily make this pattern recursive.\[\[/\1]]
ends the section with what was captured in first capturing group.
See php demo at eval.in or regex demo at regex101
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
Getting Title and Meta Tags from External Website
Http Authentication Logout Via PHP
PHP Multidimensional Array Searching (Find Key by Specific Value)
How to Query Between Two Dates Using Laravel and Eloquent
Speed Difference in Using Inline Strings VS Concatenation in PHP5
Difference Between PHP Echo and PHP Return in Plain English
How to Start and End Transaction in MySQLi
Json_Decode Returns Null After Webservice Call
How to Generate All Permutations of a String in PHP
How to Put Composite Keys in Models in Laravel 5
How to Extend a Class Using More Than 1 Class in PHP
How to Catch Curl Errors in PHP
Pdo Valid Characters For Placeholders