开发者

Running a regular expression - need to find exact location of a string patterns occurrence

This is a follow up from a previous question.

The regular expression is working fantastic however I need to be able to find out the exact location of the pattern occurrence. Like for example if my regular expression were to extract instances of the substring 'bob' from the following string:

This is abobsled

I want to also know the exact character position of the first occurrence of the pattern in the string i.e in this case its at the 10th character position - is this possible? I'm using php here.

==========================

Thanks I think I'm stuck again though - currently however this is what I want to do. Lets say I have a template of this nature:

Hello <=name=>

Take Care

From <=sender=>

Now thats easy as all th开发者_如何学编程e details are one words however in case the data to replace a tag extends over multiple lines I want to set it sup so it maintains a bit of formatting like currently the regular expression I use if I use it to replace a tag with something thats multiline I get the following:

Numbers: <=numbers=>

becomes

Numbers: number1
number2

When I want something like:

Numbers: Number1
         Number2

How can I do this :(


see: flag PREG_OFFSET_CAPTURE in http://docs.php.net/preg_match_all and/or http://docs.php.net/preg_match

E.g.

<?php
$subject = 'This is abobsled';
preg_match('/b.b/', $subject, $m, PREG_OFFSET_CAPTURE);
var_dump($m)

prints

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(3) "bob"
    [1]=>
    int(9)
  }
}
It starts counting with 0, so the 10th character is at position 9.


You can use the same regex and take position into account.

eg:

function replace_content($tag,$position, $multiline)
{
    $out='Number 1';
    $padding=implode('',array_fill(0,$position, ' '));

    if ($multiline)
    {
        $out.="\n".$padding.'Number 2';
        // etc..
    }
    return $out
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜