2

I have a string and format of substring, for example "Hello world!%1, abcdef%2, gfgf%14", i.e. format of substring is '%'+digit (0...infinity), and I need to get count of this substring in any string. I know about substring_count function, but for this function I need to know a defined line. So, please, tell me, how can I get count using regular expressions or anything else?

EDITED:

THis code works:

$r = "Hello world!%1, abcdef%2, gfgf%14";

$matches = array();
preg_match_all('/\%\d+/', $r, $matches);
echo isset($matches[0]) ? count($matches[0]) : 0;

But if I have a space before %1 or after it, the code doesn't work. Please, fix this expression. Thanks in advance.

3
  • What do you mean by "defined line"? Is your input string multiline, and yo want to know the line number of every matched occurance? Commented Jul 20, 2012 at 13:25
  • Show us your code and what you have tried. Commented Jul 20, 2012 at 13:26
  • I mean that for substring_count() I must input "%1" or anything else for searching, but I know only format - "%"+digits. Commented Jul 20, 2012 at 13:28

4 Answers 4

2
<?php

$str = "Hello world!%1, abcdef%2, gfgf%14";

$match_count = preg_match_all("/%\d+/", $str);

echo $match_count;

By the way, $matches will hold all of the matched substrings.

Sign up to request clarification or add additional context in comments.

Comments

0

Use preg_match_all with $matches array (third parameter) and then calculate length or array of occurences:

$r = "Hello world!%1, abcdef%2, gfgf%14";

$matches = array();
preg_match_all('/\%\d+/', $r, $matches);
echo isset($matches[0]) ? count($matches[0]) : 0;

3 Comments

One thing, please - modify your expression for spaces for left and right, for example "give me %1 and %2"
do you mean spaces must be present on both sides or may be present? current script says that "give me %1 and %2" has 2 occurences.
@Truth has the correct code. You don't need to count the results because preg_match_all returns the number of matches.
0

If you will never you use the % sign for anything other than defining a substring in my mind the easiest way is to do this:

$pieces = explode('%',$string);
$num_substrings = count($pieces) + 1;

Comments

0

preg_match_all returns the number of matches.

$r = "Hello world!%1, abcdef%2, gfgf%14";
echo preg_match_all('/\%\d+/', $r, $matches);
// in PHP >= 5.4 you can leave out $matches

Result:

3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.