Mukund
Mukund

Reputation: 1105

get all occurance of string between two strings in php

Hi i was looking to find an exact php equivalent of this java code

 List<String> strings = Arrays.asList(tempFinalString.replaceAll("^.*?>&", "")
            .split("<.*?(>&|$)"));

This gives an array which contain all the characters between the two characters ?> and <

Can anybody help me to find its exact php equivalent?

I searched a lot please help

Upvotes: 0

Views: 188

Answers (3)

Nandu B Nair
Nandu B Nair

Reputation: 24

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
}

Upvotes: 1

Frank
Frank

Reputation: 889

You can use regex for this

<?php
function getInbetweenStrings($start, $end, $str){
    $matches = array();
    $regex = "/$start([a-zA-Z0-9_]*)$end/";
    preg_match_all($regex, $str, $matches);
    return $matches[1];
}

$str = "<asdfasf?>dsdafs<asfasdfasf?>";
$str_arr = getInbetweenStrings('<', '\?>', $str);

print_r($str_arr);

The quite similar question is this one: Get substring between two strings PHP

EDIT

Of course for different arguments you need to change the function arguments :-)

$str = "<abcasdfasf>dsdafs<abcsfasdfasf>";
$str_arr = getInbetweenStrings('<abc', '>', $str);

print_r($str_arr);

Also be aware that the code will split the string that contains only specific characters - [a-zA-Z0-9_].

Consider learning regular expression first a bit.

Cheers!

Upvotes: 1

Nikolay Tomitov
Nikolay Tomitov

Reputation: 947

You may use pregsplit, it is pretty much the same and returns a list of strings.

Upvotes: 1

Related Questions