Page 1 of 1

Easy Regex question -

Posted: Tue Oct 28, 2008 7:56 am
by matstars
I am trying to get any text that is contained between

"<a target*>" AND "</a>"

* being a wild card

so that each of these would respond with The Quick Brown Fox:

1. <a targetafadfa>The Quick Brown Fox</a>
2. <a target>The Quick Brown Fox</a>
3. <a target in the>The Quick Brown Fox</a>


Now - as I see it -

I would need to tell regex to do the following-

Look for
1. "<a target"
2. a subsequent ">"
3. Grab ANY text following such - until you see "</a>"

I just don't know how to write that in PHP RegEx.

I used txt2re.com but there is no "any text" - so it came up with :

Code: Select all

<?php
  # URL that generated this code:
  # http://txt2re.com/index-php.php3?s=%3Ca ... -43&-6&-38
 
  $txt='<a target test>The Quick Brown Fox</a>';
 
  $re1='(<)';   # Any Single Character 1
  $re2='(a)';   # Any Single Character 2
  $re3='( )';   # Any Single Character 3
  $re4='(target)';  # Word 1
  $re5='( )';   # Any Single Character 4
  $re6='.*?';   # Non-greedy match on filler
  $re7='(>)';   # Any Single Character 5
  $re8='.*';    # Non-greedy match on filler
  $re9='(<\\/a>)';  # Tag 1
 
  if ($c=preg_match_all ("/".$re1.$re2.$re3.$re4.$re5.$re6.$re7.$re8.$re9."/is", $txt, $matches))
  {
      $c1=$matches[1][0];
      $c2=$matches[2][0];
      $c3=$matches[3][0];
      $word1=$matches[4][0];
      $c4=$matches[5][0];
      $c5=$matches[6][0];
      $tag1=$matches[7][0];
      print "($c1) ($c2) ($c3) ($word1) ($c4) ($c5) ($tag1) \n";
  }
  
  echo "<BR><BR><BR><BR>";
  echo var_dump($matches);
 
  #-----
  # Paste the code into a new php file. Then in Unix:
  # $ php x.php 
  #-----
I tried to output the array Matches - to see if I missed anything - but apparently I am doing something wrong - because it outputs:

Code: Select all

(<) (a) ( ) (target) ( ) (>) ()
 
 
 
array(8) { [0]=> array(1) { [0]=> string(38) "The Quick Brown Fox" } [1]=> array(1) { [0]=> string(1) "<" } [2]=> array(1) { [0]=> string(1) "a" } [3]=> array(1) { [0]=> string(1) " " } [4]=> array(1) { [0]=> string(6) "target" } [5]=> array(1) { [0]=> string(1) " " } [6]=> array(1) { [0]=> string(1) ">" } [7]=> array(1) { [0]=> string(4) "" } }

Any help?

-Mat

Re: Easy Regex question -

Posted: Tue Oct 28, 2008 11:47 am
by inet411

Code: Select all

preg_match_all('/<a.*target.*>.*<\/a>/',$str,$matches);
Returns
$matches[0][0] =<a targetafadfa>The Quick Brown Fox</a>
$matches[0][1] =<a target>The Quick Brown Fox</a>
$matches[0][2] =<a target in the>The Quick Brown Fox</a>

Code: Select all

preg_match_all('/<a.*target.*>(.*)<\/a>/',$str,$matches);
Returns

$matches[0][0] =<a targetafadfa>The Quick Brown Fox</a>
$matches[0][1] =<a target>The Quick Brown Fox</a>
$matches[0][2] =<a target in the>The Quick Brown Fox</a>
$matches[1][0] =The Quick Brown Fox
$matches[1][1] =The Quick Brown Fox
$matches[1][2] =The Quick Brown Fox