Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get more than one match regular expression in a string

Status
Not open for further replies.

KeziaKristina

Programmer
Nov 1, 2002
13
ID
I have a problem like this.

I have a file contain :
<HTML>
<BODY>
The amount of goods : <?php print $sesuatu; $a++; ?>
<img src='kitty.gif'>
<form action='<?php print $PHP_SELF?>'>
</BODY>
</HTML>

I want to get ALL of the string between <?php and ?>and I have tried this way:
Put all the contain of that file into a string, then i used regular expression below to find the match string.

if ($string =~ /(<\?php.*?\?>)/smg) {
$temp .= $&;}
print $temp;

But i get only the first <?php...?> , ex:
<?php print $sesuatu; $a++; ?>

How can i solve this problem?
thx
 
Hi Kezia,

Here's one way to do it:

Code:
#!perl

use strict;

#pull only lines with <php> tags from the file
open FILE, &quot;./test/test.txt&quot; or die &quot;Error: $!&quot;;
my @php = grep { /<\?php.*?\?>/gi } <FILE>;
close FILE;

#match and print the php tag contents...
foreach ( @php ) {
  /(<\?php.*?\?>)/gi;
  print &quot;$1\n&quot;;
}

This should do mostly what you want with simple tags. If there are multiple tags per line, or if one tag crosses several lines (starts at line 4, ends on line 8), this code won't work...

[hth] Notorious P.I.G.
 
if you have only one < ...> perl line, your easiest solution
is do a loop
while(<IN>){
chomp;
if ($_=~ /(<\?php.*?\?>)/smg) {....}

if not, you can do[NOT THE MOST ELEGANT SOLUTION, but should work and maybe it is what you want since you can format the different match occurences]
#assumeing you absorbed everything into a string $string
my @tmp=split/<\?php/,$string ;

foreach my $i(@tmp){die &quot;dangling <?php\n&quot;
unless $i=~/(.*)\?>/;
print &quot;match=$1\n&quot;; }


Hope this helps,
svar


 
You just need a 'while' where you have an 'if'.

[red]if[/red]
Code:
 ($string =~ /(<\?php.*?\?>)/smg) {
    $temp .= $&;}

[red]while[/red]
Code:
 ($string =~ /(<\?php.*?\?>)/smg) {
    $temp .= $&;}
'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top