-2

I have this tag on an HTML code:

text html [button link="google.com" color="#fff" text="this text here"] rest of html

I wish i could have the parameters of this "button code" in a PHP variable, but have no idea how because of Regex.

I tried using preg_match_all but no success. Like this one:

preg_match_all('/color=(\w*)/i', $text, $color);

Thanks!

5
  • Please clarify WHAT you want out of that string Commented Feb 9, 2023 at 16:41
  • 1
    Maybe you want if (preg_match_all('~(?:\G(?!^)|\[button)\s+(\w+)="([^"]*)"~', $text, $matches)) { print_r(array_combine($matches[1], $matches[2]));} - see 3v4l.org/qMqXh Commented Feb 9, 2023 at 16:44
  • 1
    \w* won't match the # character in the color attribute. Or the quotes around the attribute value. Commented Feb 9, 2023 at 16:55
  • 2
    Provide expected output, please ! Commented Feb 9, 2023 at 17:05
  • i wanted the link ready, sorry, i didnt type it. Commented Feb 9, 2023 at 22:37

2 Answers 2

1

You could use preg_match_all():

<?php

$text = 'text html [button link="google.com" color="#fff" text="this text here"] rest of html';
preg_match_all('/\[button link="(.*?)" color="(.*?)" text="(.*?)"\]/i', $text, $matches);
$link = $matches[1][0];
$color = $matches[2][0];
$text = $matches[3][0];

echo $link;
echo $color;
echo $text;

Output:

google.com
#fff
this text here
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks guys. I will post the result that worked for me. Maybe it helps someone else! The options are already in my language, portuguese. But you can understand!

I needed the script to solve the codes for more than one tag in the same HTML.

$matches = [];
        preg_match_all('/\[botao link={(.*?)} texto={(.*?)} corfundo={(.*?)} corletra={(.*?)}\]/', $text, $matches);
        
        foreach($matches[0] as $key => $match) {
            $link = $matches[1][$key];
            $texto = $matches[2][$key];
            $corfundo = $matches[3][$key];
            $corletra = $matches[4][$key];
        
            $text = str_replace($match, '<a target="_blank" title="'.$texto.'" class="botao" href="'.$link.'" style="background-color: '.$corfundo.'; color: '.$corletra.';">'.$texto.'</a>', $text);
        }

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.