JasonDavis
JasonDavis

Reputation: 48943

Needle in haystack with array in PHP

Using PHP I need I will have an array of tag name => tag URL I need to somehow scan a text input (will be somewhat large, a blog post) and find all tag names in the text and replace them with the URL link. To complicate it though, if the tag name is inside <h1>, <h2>, or <code> and <pre> tags it will not do it. Possibly to simplify, I could say it has to be inside a <p> tag for the switch to take place.

I am not sure how to accomplish this, I know I will need regex but I am a bit lost at the moment, if anyone could help me some I would greatly appreciate it

so a PHP tag would be turned into <a href="link here">PHP</a>

Upvotes: 1

Views: 634

Answers (4)

travega
travega

Reputation: 8415

You can use an XML parser like:

$array_of_tags = (array) simplexml_load_string($html);

OR

$xml_object = simplexml_load_string($html);

The first approach will give you your tags in a searchable array. The second will give you a SimpleXMLElement object.

You can then use a simple foreach loop to iterate over the elements in your array or reference the variables in your SimpleXMLElement object. Have a look at the simplexml_load_string tutorial by W3C it's very straight forward.

Upvotes: 3

jakx
jakx

Reputation: 758

I wouldn't use regex (and I don't think you would be able to) but I think you just need to get down to brass tacks on this one. Do a foreach loop and keep booleans to keep track of when you are inside an <h1> <h2> <code> or <pre>, if you are and you find something that needs to be replaced then don't replace it, otherwise replace it. Does that make sense? I can get more detailed if you want. But travega's answer is the best.

Upvotes: 1

Kristian
Kristian

Reputation: 3461

I guess you excluded h1, h2, code and pre tags have no nesting, and if you do parsing on insert then i would do:

  1. preg_replace_callback with <(h1|h2|code|pre)>(.*?)</\1>, replacing them with placeholders, and stroing them to array as placeholder => html code
  2. strtr to replace tags
  3. strtr to replace placeholders with original code

Definetly isn't a brilliant solution, but doing this only on inserting post, this shouldn't be so bad..

Upvotes: 1

user895378
user895378

Reputation:

A simple loop will suffice here:

$post = 'My link to {tag1} is awesome, but not as awesome as my link to {tag2}';

$tags = array(
  'tag1' => 'http://tag1.com',
  'tag2' => 'http://tag2.com',
  'tag3' => 'http://tag3.com',
);

foreach ($tags as $tag_name => $tag_val) {
  $post = str_replace('{'.$tag_name.'}', "<a href='$tag_val'>$tag_name</a>", $post);
}

echo $post;
// outputs:
// My link to <a href='http://tag1.com'>tag1</a> is awesome, but not as awesome as my link to <a href='http://tag2.com'>tag2</a>

Upvotes: 1

Related Questions