4

How can I get only the Name/Variable which is "regexed"? Like in this case the $1 or $0 in the anchor's href?

When I try to echo the $1 or $0 I get a Syntax Error because it's a Number. At the Moment the $str is a whole Text.

function convertHashtags($str){
    $regex = "/#+([a-zA-Z0-9_]+)/";
    $str = preg_replace($regex, '<a href="hashtag.php?tag=$1">$0</a>', $str);
    return($str);
    }
1
  • 2
    [a-zA-Z0-9_] is the same as the shorthand character class \w (word character). Commented Aug 12, 2015 at 23:18

1 Answer 1

6

Simple use preg_match before preg_replace, eg

preg_match($regex, $str, $matches);

Assuming the pattern actually matched, you should have the results in $matches[0] and $matches[1] which are the equivalent of $0 and $1 in the replace string.

FYI, the $n tokens in the replacement string are not variables though I can see how that can be confusing. They are simply references to matched groups (or the entire match in the case of $0) in the regex.

See http://php.net/manual/function.preg-replace.php#refsect1-function.preg-replace-parameters


To find multiple matches in $str, use preg_match_all(). It's almost the same only it populates $matches with a collection of matches. Use the PREG_SET_ORDER flag as the 4th argument to make the array workable. For example...

$str = ' xD #lol and #testing';
$regex = '/#(\w+)/';
preg_match_all($regex, $str, $allMatches, PREG_SET_ORDER);
print_r($allMatches);

produces...

Array
(
    [0] => Array
        (
            [0] => #lol
            [1] => lol
        )

    [1] => Array
        (
            [0] => #testing
            [1] => testing
        )

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

9 Comments

Okey now it is only showing the first result of all i guess :S ?
Ah, in that case you probably want preg_match_all(). I'll update my answer
Okey :) Sou when i have as $str=" xD #lol and #testing"; it will give me the results #lol / #testing ? Cause in the next lines i want to insert this into a Database.
Ohm there is somethin weird in your script i guess. i tested it and got the result #lollol when i echo $matches[0]; and 1 is empty
@MaddyS. Urgh, I forgot about the weird result format of preg_match_all(). Give me a second to update the answer
|

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.