How can I adapt this function below to get string between numbers?
Function:
function getInbetweenStrings($start, $end, $str){
$matches = array();
$regex = "/$start([a-zA-Z0-9_]*)$end/";
preg_match_all($regex, $str, $matches);
return $matches[1];
}
Example:
1448459casa48912687
010697046a-parede-verde698012
456902sim-senhora4401254
Output expected:
casa
a-parede-verde
sim-senhora
Thank you.
#edit: I don't want to remove all numbers, I need them! I just want grab string between.
You can use this regex, which looks for a minimal sequence (by adding ? to .*) of characters between starting and trailing digits:
^\d+(.*?)\d+$
In PHP:
$strings = array('1448459casa48912687',
'010697046a-parede-verde698012',
'456902sim-senhora4401254',
'12345number10-downing-street54321');
foreach ($strings as $string) {
$between = preg_replace('/^\d+(.*?)\d+$/', '$1', $string);
echo "$between\n";
}
Output:
casa
a-parede-verde
sim-senhora
number10-downing-street
Demo on 3v4l.org
If the strings are different (ie: [foo] & [/foo])
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 = '010697046a-parede-verde698012';
$parsed = get_string_between($fullstring, '010697046a', '698012');
echo $parsed; // (result = a-parede-verde)
Related
I have a function that extracts the content between a $start and $end inside a $string
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);
}
The problem with this is that it will only get me the first occurrence found in the string. Per example:
$text = "John has 13 oranges and Jane has 8 oranges";
$how_many_oranges = get_string_between($text,"has "," oranges");
echo $how_many_oranges; // echos "13"
I need it to find the last occurrence inside the string, so that $how_many_oranges = "8";
As mentioned in my comment, swap out strpos() for strrpos()
Find the numeric position of the last occurrence of needle in the haystack string.
Also, I believe you should change
if ($ini == 0)
to
if ($ini === false)
The former will match if $start is at the very beginning of $string. The latter will match if $start cannot be found at all.
Demo ~ https://eval.in/1027283
What about using just PHP's built in function?!
strripos() – Finds the position of the last occurrence of a string inside another string. It is a Case-insensitive.
PHP Docs
I took the liberty to rewrote your code, to make it, IMHO, more readable and self-explanatory :)
I'd also recommend you to use the strrpos:
function getStringBetween($string, $start, $end) {
$lastStartIndex = strrpos($string, $start);
$lastEndIndex = strrpos($string, $end);
$substringStartIndex = $lastStartIndex + strlen($start);
$substringSize = $lastStartIndex - $lastEndIndex - 1;
return substr($string, $substringStartIndex, $substringSize);
}
$text = "John has 13 oranges and Jane has 8 oranges";
$how_many_oranges = getStringBetween($text, "has", "oranges");
echo "'" . $how_many_oranges . "'"; // echos "' 8 '"
Try this:
function get_string_between($string, $start, $end){
$p1 = explode($start,$str);
for($i=1;$i<count($p1);$i++){
$p2 = explode($end,$p1[$i]);
$p[] = $p2[0];
}
return $p;
}
source: stackoverflow.com/a/45033158
This looks like a reasonable time to use regular expressions.
function get_string_between($string, $start, $end) {
$clean_start = preg_quote($start, '/');
$clean_end = preg_quote($end, '/');
$pattern = "/.*$clean_start (.*) $clean_end.*/U"; // U modifier => ungreedy
$default_result = ''; // returned if no matches found
$matches;
preg_match_all($pattern, $string, $matches);
return (count($matches[1]) > 0) ? end($matches[1]) : $default_result;
}
echo get_string_between('John has 13 oranges and Jane has 8 oranges', 'has', 'oranges'); // 8
$string = 'LifeSteal V \n';
I want the function to return V when I send LifeSteal and \n to a function.
If the parts to remove are always the same you can use str_replace() function passing as serach value an array with both parts you want to remove
function remove_strings($string) {
return str_replace(array('LifeSteal ', ' \n'), '', $string);
}
try below code :
function getStringBetween($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 = 'LifeSteal V \n';
$parsed = getStringBetween($fullstring, 'LifeSteal', '\n');
echo $parsed;
I've been searching a lot but i cannot find anything similar to my problem. I've found this link but i don't think they really answered the question.
Let say i have this string
$my_string = "I am with a [id]123[/id] and [id]456[id]";
I want to get all the number between [id][/id]. I only have this function to get the string between.
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 = 'I am with a [id]123[/id] and [id]456[id]';
$parsed = get_string_between($fullstring, '[id]', '[/id]');
But this function only returns the first string found on $fullstring. Maybe i can get 123,456 or in array form array('123','456'). I really am stuck with this.
You can simply use preg_match_all function of the PHP along with following regex
~\[id\](.*?)\[\/id\]~
like as
$my_string = "I am with a [id]123[/id] and [id]456[/id]";
preg_match_all("~\[id\](.*?)\[\/id\]~",$my_string,$m);
print_r($m[1]);
Is there a PHP function that can extract a phrase between 2 different characters in a string? Something like substr();
Example:
$String = "[modid=256]";
$First = "=";
$Second = "]";
$id = substr($string, $First, $Second);
Thus $id would be 256
Any help would be appreciated :)
use this code
$input = "[modid=256]";
preg_match('~=(.*?)]~', $input, $output);
echo $output[1]; // 256
working example http://codepad.viper-7.com/0eD2ns
Use:
<?php
$str = "[modid=256]";
$from = "=";
$to = "]";
echo getStringBetween($str,$from,$to);
function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}
?>
$String = "[modid=256]";
$First = "=";
$Second = "]";
$Firstpos=strpos($String, $First);
$Secondpos=strpos($String, $Second);
$id = substr($String , $Firstpos, $Secondpos);
If you don't want to use reqular expresion, use strstr, trim and strrev functions:
// Require PHP 5.3 and higher
$id = trim(strstr(strstr($String, '='), ']', true), '=]');
// Any PHP version
$id = trim(strrev(strstr(strrev((strstr($String, '='))), ']')), '=]');
Regular Expression is your friend.
preg_match("/=(\d+)\]/", $String, $matches);
var_dump($matches);
This will match any number, for other values you will have to adapt it.
You can use a regular expression:
<?php
$string = "[modid=256][modid=345]";
preg_match_all("/\[modid=([0-9]+)\]/", $string, $matches);
$modids = $matches[1];
foreach( $modids as $modid )
echo "$modid\n";
http://eval.in/9913
$str = "[modid=256]";
preg_match('/\[modid=(?P<modId>\d+)\]/', $str, $matches);
echo $matches['modId'];
I think this is the way to get your string:
<?php
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 = '.layout {
color: {{ base_color }}
}
li {
color: {{ sub_color }}
}
.text {
color: {{ txt_color }}
}
.btn {
color: {{ btn_color }}
}
.more_text{
color:{{more_color}}
}';
$parsed = get_string_between($fullstring, '{{', '}}');
echo $parsed;
?>
(moved from comment because formating is easier here)
might be a lazy approach, but in such cases i usually would first explode my string like this:
$string_array = explode("=",$String);
and in a second step i would get rid of that "]" maybe through rtrim:
$id = rtrim($string_array[1], "]");
...but this will only work if the structure is always exactly the same...
-cheers-
ps: shouldn't it actually be $String = "[modid=256]"; ?
Try Regular Expression
$String =" [modid=256]";
$result=preg_match_all('/(?<=(=))(\d+)/',$String,$matches);
print_r($matches[0]);
Output
Array ( [0] => 256 )
DEMO
Explanation
Here its used the Positive Look behind (?<=)in regular expression
eg (?<=foo)bar matches bar when preceded by foo,
here (?<=(=))(\d+) we match the (\d+) just after the '=' sign.
\d Matches any digit character (0-9).
+ Matches 1 or more of the preceeding token
You can use a regular expression or you can try this:
$String = "[modid=256]";
$First = "=";
$Second = "]";
$posFirst = strpos($String, $First); //Only return first match
$posSecond = strpos($String, $Second); //Only return first match
if($posFirst !== false && $posSecond !== false && $posFirst < $posSecond){
$id = substr($string, $First, $Second);
}else{
//Not match $First or $Second
}
You should read about substr. The best way for this is a regular expression.
I am trying to get sub string in between two sub strings in string. By using this code
I am getting first sub string only. Can you please say how can I get all sub strings?
Thanks
Sateesh
Using code:
<?php
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "[tag]php[/tag] [tag]java[/tag] ";
$count = substr_count($fullstring, '[tag]');
for($i=0; $i<$count;$i++){
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");
echo "LineItems[$i]:".$parsed."<br>";
}
?>
$matches = array();
preg_match('#\[tag\]([^\[]+)\[/tag\]#', "[tag]php[/tag] [tag]java[/tag] ", $matches)
$matches == array("[tag]php[/tag] [tag]java[/tag] ", 'php','java');
array_shift($matches);
$matches == array('php','java');
Something along those lines, try incorporating that into your function
This should do what you're looking for using a regular expression. Do note that it won't work if you have multiple [tag]s nested within eachother.
<?
$fullstring = "[tag]php[/tag] [tag]java[/tag]";
$matches = array();
preg_match_all('#\[tag\](.*?)\[/tag\]#', $fullstring, $matches);
foreach ($matches[1] as $match) {
// Do whatever you need to do with the matches here.
echo "$match<br/>";
}