Home > Software engineering >  Convert text in Brackets [[]] to clickable links in PHP
Convert text in Brackets [[]] to clickable links in PHP

Time:01-19

I am trying to convert simple wikitext into html for my personal website. How I can convert

[[Apples|Apple]]

to

<a href="javascript:void(0)" style="color:blue" data-href="dict.php?word=Apple" >Apples</a>

and in the same text

[[Apple]]

to

<a href="javascript:void(0)" style="color:blue" data-href="dict.php?word=Apple" >Apple</a>

CodePudding user response:

There's a few different issues.

  • Finding the pattern in a string '!\[\[(.*?)\]\]!'
  • Stripping out the [[]]
  • Taking a result, and exploding on '|'

This is a proof of how to do it. I leave it to you to modify the anonymous function code to take the parameters and add the rest of the html code you need. That should be simple, assuming you understand the code I provided.

<?php

$source = "Some text and [[apples|apple]] followed by [[orange]]";

$pattern = '!\[\[(.*?)\]\]!';
$matches = array();

$newstring = preg_replace_callback(
    $pattern,
    function($match) {
        
        $tmp = explode('|', str_replace(array('[',']'), '', $match[0]));
        $value = count($tmp) > 1 ? $tmp[1] : $tmp[0];
        return "parm1:$tmp[0] - parm2:$value"; 
    },
    $source
);
echo $newstring;

CodePudding user response:

Use a branch reset group:

$pattern = '~
    \Q[[\E
    (?|
        ( [^][|]* ) \| ( [^]]* )
      |
        ( ( [^][|]* ) )
    )
    ]]
~x';

$replacement = '<a href="javascript:void(0)" data-href="dict.php?word=$2" >$1</a>';

$result = preg_replace($pattern, $replacement, $yourstring);

I removed the style attribute, you can put it in a css stylesheet since the links have all the same class attribute.

CodePudding user response:

<?php

class Replace 
{
    private $text;
    private $patternArr = [
        '/\[\[([^\[\]\|] )\]\]/',
        '/\[\[(. )\|(. )\]\]/U',
    ];

    public function __construct(string $text)
    {
        $this->text = $text;
        $this->subsitute();
    }

    public function __toString() : string
    {
        return $this->text;
    }

    private function subsitute() : void
    {
        foreach ($this->patternArr as $key => $patternStr) {
            $stat = preg_match_all($patternStr, $this->text, $matches);
            if ($stat === false) {
                throw new \RuntimeException('Something went wrong with pattern: ' . $patternStr . ' and text: ' . $this->text);
            }

            if ($stat > 0 && $key == 0) {
                $search = $matches[0][0];
                $word = $matches[1][0];
                $replace = '<a href="javascript:void(0)" style="color:blue" data-href="dict.php?word='. $word . '" >'. $word .'</a>';
                $this->text = str_replace($search, $replace, $this->text);
            }

            if ($stat > 0 && $key == 1) {
                $search = $matches[0][0];
                $word1 = $matches[1][0];
                $word2 = $matches[2][0];
                $replace = '<a href="javascript:void(0)" style="color:blue" data-href="dict.php?word=' . $word2 . '" >' . $word1 . '</a>';
                $this->text = str_replace($search, $replace, $this->text);
            }

        }
    }
    
}

$text = "This is a text [[Apples|Apple]] having also an [[Apple]]";

$replace = new Replace($text);

echo "Text:\n";
echo "$text\n";

echo "\n";

echo "Replacement:\n";
echo "$replace\n";

returns:

Text:
This is a text [[Apples|Apple]] having also an [[Apple]]

Replacement:
This is a text <a href="javascript:void(0)" style="color:blue" data-href="dict.php?word=Apple" >Apples</a> having also an <a href="javascript:void(0)" style="color:blue" data-href="dict.php?word=Apple" >Apple</a>

References:

Regex patterns:

/[[([^[]|] )]]/

/[[(. )|(. )]]/U

Keywords:

class Replace

new Replace($text)

Functions:

public function __construct(string $text)

public function __toString() : string

preg_match_all

str_replace


  •  Tags:  
  • Related