Getting total sub strings in the string - php

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/>";
}

Related

Get string between numbers using PHP

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)

How to get the last occurrence of a string?

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

How to search string in string php?

I'm searching one PHP function or other solution for my problem.
So, I have a string, this:
$string = 'dfdfdjdkfjsdklfjdksfjekrjekjfdlkfjsdlfdflokuki48(malac)kjdkfdjfkjkejrkerjer';
I'm searching one function, that it has the next parameters:
functionName ($string, $fromCharacters, $toCharacters);
And I run this function:
functionName ($string, 'lokuki48(', ')');
And I will get this: 'malac', or max. this: 'lokuki48(malac)'.
Do you know about PHP function or solution for my problem?
I hope you understand my problem.
Thank you!
try this,
$string = 'dfdfdjdkfjsdklfjdksfjekrjekjfdlkfjsdlfdflokuki48(malac)kjdkfdjfkjkejrkerjer';
if (strpos($string, 'malac') !== false)
{
echo 'true';
}
else
{
echo 'false';
}
https://3v4l.org/SiPvO
i hope it will be helpful.
The strstr() function searches for the first occurrence of a string inside another string.
Example
Find the first occurrence of "world" inside "Hello world!" and return the rest of the string:
<?php
echo strstr("Hello world!","world");
?>
Thanks Guys!
I have found the solution:
`$string = 'dfdfdjdkfjsdklfjdksfjekrjekjfdlkfjsdlfdflokuki48(fasza)kjdkfdjfkjkejrkerjer';
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);
}
echo get_string_between($string,"lokuki48(",")");`
If you love lókuki, use preg_match:
<?php
function search($string, $start, $end)
{
preg_match("'".$start."(.*)".$end."'sim", $string, $out);
if(isset($out[1])) {
return $out[1];
}
return false;
}
$string = 'dfdfdjdkfjsdklfjdksfjekrjekjfdlkfjsdlfdflokuki48(malac)jdkfdjfkjkejrkerjer';
$start="lokuki48\(";
$end="\)";
$res = search($string, $start, $end);
echo $res."\n\n";
$string = 'dfdfdjdkfjsdklfjdksfjekrjekjfdlkfjsdlfdftestfunction(param1, param2)jdkfdjfkjkejrkerjer';
$start="testfunction\(";
$end="\)";
$res = search($string, $start, $end);
echo $res;

Extract a substring between two characters in a string PHP

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.

How can I find each instance of a string inside two other strings (Tags)

The code I'm using searches for a string inside two other strings (tags). The string it searches through is a list of ID's. The ID's are listed in between tags. My code can successfully pull and list one ID, but is there a way to loop it and have it pull them all and assign them to variables or an array?
Here is the code:
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);
}
$resumeid = get_string_between($xml, "<ResumeID>", "</ResumeID>");
echo $resumeid;
I tried using the foreach() function, but it didn't seem to work:
foreach( $resumeid as $item )
{
echo $item.'<br />';
}
How would I accomplish this?
You need to loop the function not just the results of the function alternatively just use regular expressions rather than a complicated series of string functions will be much easier.
preg_match_all("/(<ResumeID>)(\w+)(<\/ResumeID>)/", $xml, $matches);
foreach ($matches[0] as $match)
{
echo $match."<br />";
}

Categories