CodeClerks

php wrap specific word in text string with html tags



Write the reason you're deleting this FAQ

php wrap specific word in text string with html tags

This is a small function to wrap a specific word in a text string with a html tag. So lets say I want to wrap the third word in

<b></b>
tags I would use below.

echo WrapWord('This is my line of text!', '3', 'b');

Above would output "This is my line of text!" you will need the function for above to work otherwise it will most likely display a blank page, The function WrapWord(); is below.


function WrapWord($text, $position, $tag) {
   $ex = explode(' ', $text);
   foreach ($ex as $key => $val) {
      if ($key == $position-1) {
         $val = "<${tag}>${val}</${tag}>";
      }
      $word_string .= "${val} ";
   }
      return $word_string;
}
 


some other examples below.


echo WrapWord('This is my line of text!', '4', 'i');
//Outputs "This is my <i>line</i> of text!"

echo WrapWord('This is my line of text!', '2', 'p');
//Outputs "This <p>is</p> my line of text!"

echo WrapWord('This is my line of text!', '1', 'span');
//Outputs "<span>This</span> is my line of text!"
 


and a full mark up of the php file.


<?php
function WrapWord($text, $position, $tag) {
   $ex = explode(' ', $text);
   foreach ($ex as $key => $val) {
      if ($key == $position-1) {
         $val = "<${tag}>${val}</${tag}>";
      }
      $word_string .= "${val} ";
   }
      return $word_string;
}


echo WrapWord('This is my line of text!', '3', 'b');
?>
 


Hope this comes in useful to some people.
~Jake

Comments

Please login or sign up to leave a comment

Join
sunil0021
Thanks for sharing jake php wrap specific word in text string with html tags Now a days i'm learning php for wordpress development, i will contact you in future if i need any complex language work php wrap specific word in text string with html tags

- Sunil Bishnoi



Are you sure you want to delete this post?