1

Hi so I need help in taking a block of html which contains existing shortcode for an old arbitrary system. Taking the code below and and using PHP change so the following :

[CDC](http://www.cdc.gov/)

would be transformed into this :

<a href="http://cdc.gov">CDC</a> 

Any ideas on how i could achive this? There could be multiple instances in one block of code also. If anybody can help , I'd be grateful - thank you!!

6
  • There could be multiple instances in one block of code also - how that, can you visualize such case? Commented Jan 9, 2017 at 18:48
  • Not sure what you mean but as an example - this block of text: "Two excellent websites outlining the major precautions are: 'www.cdc.gov' and 'www.who.int' which are the official sites for the centers of disease control prevention and the World health organization respectively." has 2 instances of the shortcode. I'd need it to convert both instances to their respective links. Commented Jan 9, 2017 at 18:50
  • Ahh - ironically SE is changing the shortcodes as they are in my comment :( - its exactly what i need wow Commented Jan 9, 2017 at 18:53
  • so, those occurrences like 'www.cdc.gov' actually look like [TEXT]('www.cdc.gov') in source code? Commented Jan 9, 2017 at 18:54
  • Exactly. [LINK_TEXT](LINK_URL) Commented Jan 9, 2017 at 18:57

2 Answers 2

3

The solution using preg_replace function with specific regex pattern:

$block = "Two excellent websites outlining the major precautions are: [some text](www.cdc.gov) and [who's next](www.who.int) which are the official sites ...";

$block = preg_replace("/\[([^]]+)\]\(([^)]+)\)/", '<a href="$2">$1</a>', $block);

print_r($block);

The output(from source code):

Two excellent websites outlining the major precautions are: <a href="www.cdc.gov">some text</a> and <a href="www.who.int">who's next</a> which are the official sites ...
Sign up to request clarification or add additional context in comments.

Comments

0

This should Work:

PHP:

<?php 
$re = '/(?<=\[)[^]]+(?=\])|(?<=\()[^]]+(?=\))/m';
$str = '[CDC](http://www.cdc.gov/)';

preg_match_all($re, $str, $matches);

// Print the entire match result
//print_r($matches); //Print result
$url = $matches[0][1]; //http://www.cdc.gov/
$text_url = $matches[0][0]; //CDC
echo "<a href=".$url.">$text_url</a>"
 ?>

Result:

<a href=http://www.cdc.gov/>CDC</a>

Enjoy.

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.