View Full Version : How do I extract a part of a string?
jacksont123
01-29-2007, 12:45 AM
Say I have the string:
blasblahblooblezIneedtoextractthisboozblosblooblaheedsdfds
How do I extract whatever is in between "blez" and "booz"?
BLiZZaRD
01-29-2007, 01:10 AM
That's a double question... double edged at that.
Unless I am completely not understanding you, what is creating the string, where is it located, are you wanting to pull it out to display it on a page? Is it going to be saved off by itself? What do you want to pull it out with? Will it always be text, always the same length, etc etc.
A little more on what you want to accomplish will help answer those questions :)
jacksont123
01-29-2007, 01:10 AM
I found this script somewhere that does the same function but its in javascript.
<script type="text/javascript">
<!-- //
function CodeFix()
{
var strEmbedCode=new String (document.getElementById("txtEmbedCode").value);
var strStartMatch=new String("blez");
var strEndMatch=new String("blez");
var intStart=0;
var intEnd=0;
intStart=strEmbedCode.indexOf(strStartMatch, 0) + strStartMatch.length;
intEnd=strEmbedCode.indexOf(strEndMatch, intStart);
if ((intStart != -1) && (intEnd !=-1))
{
strEmbedCode=strEmbedCode.substring(intStart, intEnd);
strEmbedCode=unescape(strEmbedCode);
/*document.location.href=strEmbedCode;*/
window.location=strEmbedCode;
document.getElementById("downloadlink").innerHTML=strEmbedCode;
return true;
}
else
{
alert("Input format incorrect!");
}
}
// -->
</script>
jacksont123
01-29-2007, 01:12 AM
That's a double question... double edged at that.
Unless I am completely not understanding you, what is creating the string, where is it located, are you wanting to pull it out to display it on a page? Is it going to be saved off by itself? What do you want to pull it out with? Will it always be text, always the same length, etc etc.
A little more on what you want to accomplish will help answer those questions :)
The string will be displayed on the page, and the original may not be the same.
I just need to extract what ever is in between "blez" and "booz" and display it on the page.
mburt
01-29-2007, 01:17 AM
var query = "blez"
var string = "blasblahblooblezIneedtoextractthisboozblosblooblaheedsdfds"
alert(string.substring(string.indexOf(query),string.indexOf(query)+query.length))
do the same for booz or whatever
jacksont123
01-29-2007, 01:29 AM
Is that for php or javascript?
and will that extract and display whatever is in booz and blez?
(sorry, i would have made better words but i couldn't think of anything at the time)
djr33
01-29-2007, 01:35 AM
EDIT: Apparently the original post was edited, changing the question. The answer relating to the new question is on the next page.
However, this applies well (and fills in some details missing in the next post) if you want to find "blez" AND "blez", or two of the same markers, not different markers.
Several methods...
1.
list($extra,$YOURVAR,$extra2) = explode('blez',$string,3);
$YOURVAR now holds that value.
2.
$YOURVAR = substr($string,strpos($string,'blez')+strlen('blez'),(strpos($string,'blez',strpos($string,'blez')+strlen($marker))-(strpos($string,'blez')+strlen('blez'))));
Again, $YOURVAR now holds the value.
I think the substr method would theoretically best less server load or some such, but, hey, I think explode is a little bit friendlier ;)
More info:
1.
list() acts like an array, but with specific variables. You could just use $myvar = explode(...) instead, and $myvar[1] (since arrays start at zero, 1 is the second value) would be what you want.
explode() splits a string into chunks (in an array) at a marker. The third parameter is limiting the number of outputs to three, so the next blez, if it were to occur would not split again, causing confusion.
2. substr(STRING, INT START, INT LENGTH) (aka sub-string)
So... you set which string to use, what point to start and how long it should be. This can all be determined using strpos() (aka string-position, within a string):
strpos(STRING, INT START, INT OFFSET)
So... which string, where to start, then, if added, how far into the string to start looking. We use this here because you need two instances of the same string, so you need to be sure not to just find the first occurance twice.
Note: strlen($var) just returns to length of $var, helping with the offset and such.
For a better understanding of method two, here are two ways to look at it:
First, make it generic. Let's use a variable instead of your randomly chosen marker:
$marker = 'blez';
substr($string,strpos($string,$marker)+strlen($marker),(strpos($string,$marker,strpos($string,$marker)+strlen($marker))-(strpos($string,$marker)+strlen($marker))));
Now, to further explain, we can seperate that into lots of parts:
$marker = 'blez';
//Here's what we're starting with--
substr($string,strpos($string,$marker)+strlen($marker),(strpos($string,$marker,strpos($string,$marker)+1)-(strpos($string,$marker)+strlen($marker))));
//To begin...
$len = strlen($marker); //$len is now length of marker
$pos1 = strpos($string,$marker); // find pos1 (first position) of marker in string
//already, it looks a lot simpler:
substr($string,$pos1+$len,(strpos($string,$marker,$pos1+$len)-($pos1+$len)));
//Now, to continue:
substr($string,$pos1+$len,(strpos($string,$marker,$pos1+$len)-($pos1+$len)));
//We don't want to include the marker, so let's add it's length to the starting point--
$start = $len + $pos1;
//Now, even more simple:
substr($string,$start,(strpos($string,$marker,$start)-$start));
//Let's find the second occurance of $marker:
$pos2 = strpos($string,$marker,$start);
//find position of $m in $s AFTER starting point, $start
//So...
substr($string,$start,($pos2-$start));
//Let's simplify the end...
//Since we want what is BETWEEN $start and $pos2, let's just subtract:
$length = ($pos2-$start);
//Now, looks a lot nicer:
substr($string,$start,$length);
//So, here's all of that without the 'work':
$len = strlen($marker);
$pos1 = strpos($string,$marker);
$start = $len + $pos1;
$pos2 = strpos($string,$marker,$start);
$length = ($pos2-$start);
$MYVAR = substr($string,$start,$length);
EDIT: Note that in the time it took me to write all of the comments and such, I now find 5 posts have been added... I *was* going to be the first reply :p
mburt
01-29-2007, 01:35 AM
Sorry, my internet disconnected me! I couldn't finish my post.
And I forgot this was in the php section.. whoa I'm sleep deprived...
This is a javascript way to do it:
<script type="text/javascript">
function getstr(query1,query2,string) {
document.write(string.substring(string.indexOf(query1)+query1.length,string.indexOf(query2)));
}
var string1 = "blasblahblooblezIneedtoextractthisboozblosblooblaheedsdfds"
var myquery1 = "blez"
var myquery2 = "booz"
getstr(myquery1,myquery2,string1)
</script>
mburt
01-29-2007, 01:37 AM
indexOf, and strpos are almost identical between JavaScript and PHP. Either way works.
mburt
01-29-2007, 01:37 AM
thetestingsite: I changed it to document.write, I got cut off and couldn't edit my post.
thetestingsite
01-29-2007, 01:38 AM
It's ok, I deleted my post becuase you and djr33 got it taken care of.
mburt
01-29-2007, 01:40 AM
Now it looks like I'm talking to myself :p
djr33
01-29-2007, 01:47 AM
Oh, great. I misread the post :p
The above works for 'blez' AND 'blez'...
Here's the version with two variables:
$m1 = 'blez';
$m2 = 'booz';
//version 1:
list($null,$yourvar) = explode($m1,$string,2);
list($yourvar,$null) explode($m2,$string,2);
//$yourvar now = contents
//version 2:
substr($string,strpos($string,$m1)+strlen($m1),(strpos($string,$m2,strpos($string,$m1)+strlen($m1))-(strpos($string,$m1)+strlen($m1))));
EDIT: Nevermind... you HAD posted: 'blasblahblooblezIneedtoextractthisblezblosblooblaheedsdfds'
It's helpful not to change the original question. Heh.
And, here you go if you want the more expanded version:
$m1 = 'blez';
$m2 = 'booz';
$len1 = strlen($m1);
$pos1 = strpos($string,$m1);
$start = $len1 + $pos1;
$pos2 = strpos($string,$marker,$start);
$length = ($pos2-$start);
$MYVAR = substr($string,$start,$length);
mburt
01-29-2007, 01:59 AM
Yeah, kind of confusing at first. I thought she/he just wanted to search a string, not look between two :p
BLiZZaRD
01-29-2007, 02:14 AM
So did I mburt... which is why I asked for clarification.
I think this is just a test and we will come back tomorrow to find the original question changed to:
"How can I make a script to change my hair color?"
And the OP will sit and laugh at the chaos s/he has created :D
mburt
01-29-2007, 11:08 AM
Thinking for OP:
MWAHAHAHAHAH, look what simple chaos I have created. *twittles fingers lightly :D
jacksont123
02-03-2007, 11:20 PM
so it seems that this actually worked for me [thanks djr33!]:
$string = "dededehellodynamicdrivebye3kdoe";
$m1 = "hello";
$m2 = "bye";
$extractedstring = substr($string,strpos($string,$m1)+strlen($m1),(strpos($string,$m2,strpos($string,$m1)+strlen($m1))-(strpos($string,$m1)+strlen($m1))));
echo $extractedstring;
The result would be dynamicdrive
The problem is that if I had a string that had multiple lines such as
dededehellodynamicdrivebye3kdoe
zoomzoomzoomhellodynamicdriverulesbyemoomoopoe
sdf4rfdfhellodynamicdriverulesmysocks!byedsgf4fds
324efdshellotehdynamicdrivepwnz0rzmysocksbyedsrewr3
I would only be able to extract "dynamicdrive".
How do I extract all the lines in green? Would I have to create an array or something? I'm not really sure:confused:.
substr($string,strpos($string,$m1)+strlen($m1),(strpos($string,$m2,strpos($string,$m1)+strlen($m1))-(strpos($string,$m1)+strlen($m1))));And now we see why regex is so handy. :p
$str = '324efdshellotehdynamicdrivepwnz0rzmysocksbyedsrewr3';
$pattern = '/hello(.*?)bye/';
$matches = array();
preg_match($pattern, $str, $matches);
print $matches[1]; // Prints "tehdynamicdrivepwnz0rzmysocks"
mburt
02-04-2007, 12:37 AM
Lol... I didn't even think of Regular Expressions in the first place. How stupid was that :p
jacksont123
02-04-2007, 12:45 AM
But how could I make it so that the input which is the following:
dededehellodynamicdrivebye3kdoe
zoomzoomzoomhellodynamicdriverulesbyemoomoopoe
sdf4rfdfhellodynamicdriverulesmysocks!byedsgf4fds
324efdshellotehdynamicdrivepwnz0rzmysocksbyedsrewr3
Becomes to this output:
dynamicdrive
dynamicdriverules
dynamicdriverulesmysocks!
tehdynamicdrivepwnz0rzmysocks
mburt
02-04-2007, 01:02 AM
Look at Twey's post. It uses RegExp to search/display the string queried.
jacksont123
02-04-2007, 01:06 AM
If I put this as my string:
dededehellodynamicdrivebye3kdoe
zoomzoomzoomhellodynamicdriverulesbyemoomoopoe
sdf4rfdfhellodynamicdriverulesmysocks!byedsgf4fds
324efdshellotehdynamicdrivepwnz0rzmysocksbyedsrewr3
I would only get:
dynamicdrive
Instead of:
dynamicdrive
dynamicdriverules
dynamicdriverulesmysocks!
tehdynamicdrivepwnz0rzmysocks
$str = '324efdshellotehdynamicdrivepwnz0rzmysocksbyedsrewr3';
$pattern = '/hello(.*?)bye/';
$matches = array();
preg_match($pattern, $str, $matches);
print $matches[1]; // Prints "tehdynamicdrivepwnz0rzmysocks"
How do I make it so it prints all the matches?
djr33
02-05-2007, 09:27 PM
split at each line ("\n") then just do the same thing for each. Setup a function if needed.
regex... I should figure that out. clearly helpful...
jacksont123
02-05-2007, 09:58 PM
Could you please give me an example?
djr33
02-06-2007, 03:49 AM
foreach (explode("\n",$text) as $line) {
do_stuff_here;
}
Note: variable "$line" will have the info for each line during that loop, so search that, etc. I'd recommend saving the values into an array or displaying... all depends what you want.
If you just want them assembled, use:
$newtext .= "\n".$linecut;
(where $linecut has been split as you want... copy/paste from before)
No, use preg_match_all():
<?php
$str = <<<END
dededehellodynamicdrivebye3kdoe
zoomzoomzoomhellodynamicdriverulesbyemoomoopoe
sdf4rfdfhellodynamicdriverulesmysocks!byedsgf4fds
324efdshellotehdynamicdrivepwnz0rzmysocksbyedsrewr3
END;
$pattern = '/hello(.*?)bye/m';
$matches = array();
preg_match_all($pattern, $str, $matches);
$matches = $matches[1];
// $matches is now an array of all the values.
?>
djr33
02-07-2007, 04:27 AM
$matches .= $match[1] ?
Edit: nevermind. But why [1]?
[1] is the array of backreferences. See preg_match_all (http://www.php.net/preg-match-all)().
while (list($value) = each($matches)) { ... the heck are you doing there? Single-value list()s?
foreach($matches as $v)
print $value . '<br>';
jacksont123
02-10-2007, 02:48 PM
No, use preg_match_all():
<?php
$str = <<<END
dededehellodynamicdrivebye3kdoe
zoomzoomzoomhellodynamicdriverulesbyemoomoopoe
sdf4rfdfhellodynamicdriverulesmysocks!byedsgf4fds
324efdshellotehdynamicdrivepwnz0rzmysocksbyedsrewr3
END;
$pattern = '/hello(.*?)bye/m';
$matches = array();
preg_match_all($pattern, $str, $matches);
$matches = $matches[1];
// $matches is now an array of all the values.
?>
... the heck are you doing there? Single-value list()s?
foreach($matches as $v)
print $value . '<br>';
I wrote my code wrong in the previous post.
I changed it so it would be
while (list($key,$value) = each($matches)) {echo "$value<br />";}
and it worked fine.
Thanks a lot Twey!
Still uglier than foreach.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.