0

I have this text string:

$text="::tower_unit::7::/tower_unit::<br/>::tower_unit::8::/tower_unit::<br/>::tower_unit::9::/tower_unit::";

Now I want to get the value of 7,8, and 9 how to do that in preg_match_all ?

I've tried this:

$pattern="/::tower_unit::(.*)::\/tower_unit::/i";
preg_match($pattern,$text,$matches);

print_r($matches);

but it still all wrong...

2 Answers 2

5

You forgot to escape the slash in your pattern. Since your pattern includes slashes, it's easier to use a different regex delimiter, as suggested in the comments:

$pattern="@::tower_unit::(\d+)::/tower_unit::@"; 
preg_match_all($pattern,$text,$matches);

I also converted (.*) to (\d+), which is better if the token you're looking for will always be a number. Plus, you might want to lose the i modifier if the text is always lower cased.

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

5 Comments

I never really understood why people insist on using / as the start/end character, especially when it's used in the pattern itself.
@Mark: If you come from a JavaScript or Ruby background (where the slash is the only possible delimiter), you might not expect that you can freely choose your delimiter in PHP/Perl.
@Mark I'm guessing most don't know you can use a different character, as almost all the popular PHP examples for some reason use /
@Mark i agree with Dor... i never realize i can use different character.. in my 7 years using php, i just realize it.. how ironic..
@Viktor: Well I'm glad I taught you something new then ;) It can be quite handy sometimes. URLs come to mind.
0

Your regex is "greedy". Use the following one

$pattern="#::tower_unit::(.*?)::/tower_unit::#i";

or

$pattern="#::tower_unit::(.*)::/tower_unit::#iU";

and, if you wish, \d+ instead of .*? or .*

the function should be preg_match_all

2 Comments

btw, could you give reference what 'U' means in the last character of pattern... what possible between i and U
@Viktor U means "ungreedy", without it .* will get everything until the last match. Without modificator U .*? can be used. i means "case-insensitive", so [a-z] is the same as [a-zA-Z] or any words in regexp will not depend on the case. Read here php.net/manual/en/reference.pcre.pattern.modifiers.php

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.