Page 1 of 1

how to find the number of tokens using regular expression?

Posted: Mon Oct 18, 2004 2:18 am
by jasongr
Hello

Assuming I have a sentence like so:
"Hello %1, I %3 %4 five days day ago. %5 need to talk to %6 later"

The sentence has wild cards that can be used as placeholders for actual strings which will replace the tokens.
Such replacement can yield the sentence
"Hello Jeff, I saw you five days day ago. I need to talk to you later"
The sentence above has 6 such placeholders.

Here is my question:
Given such sentence, how can I tell how many wild cards it has?
Note that the number isn't limited to 1-9 but theoretically be very high.

I tried to use split with regular expressions but I must be using the wrong regular expression (I am fairly new to them).

I would appreciate any help

Posted: Mon Oct 18, 2004 2:24 am
by feyd

Code: Select all

preg_replace('#(?!=%)%(\d+)#e', '$substitutionї\\\\1-1]', $text);

Posted: Mon Oct 18, 2004 2:29 am
by jasongr
I am not sure I understand your regular expression.
I didn't notice that you are using preg_replace.

I don't want to replace anything in my original string.
I just want to know how many placeholders there are in the string.

In my original example there were 6 of them.
I don't want any side effects like having those placeholders replaced by tokens

Posted: Mon Oct 18, 2004 2:34 am
by feyd
for counting, just switch the pattern over to preg_match_all ... (losing the e modifier)

Posted: Mon Oct 18, 2004 2:55 am
by jasongr
Here is what I tried:

Code: Select all

$string = 'Welcome %1, nice to meet you';
$numTokens = preg_match_all('/%\d+/', $string, $outTokens);
But I am getting $numTokens = 0 instead of 1

Posted: Mon Oct 18, 2004 2:57 am
by feyd
I sure get 1.

Posted: Mon Oct 18, 2004 3:04 am
by jasongr
You are right - my mistake
I was feeding it the wrong string.

thanks for the help - it works

Posted: Mon Oct 18, 2004 3:09 am
by feyd
just for further correction of my first post

Code: Select all

<?php

$string = 'Welcome %1, nice to meet you. %%1 is a lonely number.';
echo $numTokens = preg_match_all('#(?<!%)%(\d+)#', $string, $outTokens);
var_export($outTokens);

?>

Code: Select all

1
array (
  0 =&gt;
  array (
    0 =&gt; '%1',
  ),
  1 =&gt;
  array (
    0 =&gt; '1',
  ),
)
in case you want to be able to "escape" your placeholder :)

Posted: Mon Oct 18, 2004 8:09 am
by jasongr
thanks
this is quite useful