PHP: Picking up function argument with preg_match_all

Asked

Viewed 987 times

3

Good afternoon:

I’m picking up to pick up the value of calls to a certain PHP function straight from the source code.

What I need to do is sweep each of the lines of the source code, and if there is one or more function calls altext(), take the argument passed. For example:

<img alt="<?php echo altext('[Este é um texto alternativo]');?>">

In the case of the example, I need to return only "This is an alternative text" (without quotation marks). The [] were placed to prevent that, having a ') in the middle of the text, the search stops before the end. I’m trying to use preg_match_all("/\[altext\]\(\'\[(.*)\]\'\)/", $data, $matches); but nothing is returning. $data is the line of code I seek from source code with fgets.

  • You’re making a print_r($matches) ?

  • Yes, the result is: Array ( [0] => Array ( ) [1] => Array ( ) ;)

  • In the source code is this phrase "This is an alternate text" ? And you want to get it ? Are you sure your regex is right ?

  • That’s the problem: regex is not my strong suit, so I’ve been studying the subject, but I’m not seeing the problem.

  • Try using that: (\W|^)este é um texto alternativo(\W|$).

  • In this case, it will only find what has "this is an alternative text". However, I have several calls to the function altext(), but each with a different argument. what interests me is the argument of the function, whatever it is.

  • Just pass the variable inside the regex. Isn’t it ? (\\W|^)$var(\\W|$)

Show 2 more comments

2 answers

1


I got it from reading a text from Martin Streicher and of Manual for PHP

preg_match_all("/altext\(\'(.*)\'\)/", $data, $matches);

And yet it requires no other artifice if a ') appears in the middle of the argument.

I can’t believe it was so easy. I looked for days.

  • no need to escape single quotes, can use only: /altext\('(.*)'\)/. Recommended reading: http://aurelio.net/regex/guia/

0

I put as an answer Everton.

$re = "/(\\W|^)este é um texto alternativo(\\W|$)/"; 
preg_match_all($re, $data, $matches);

print_r($matches)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.