...

View Full Version : Placing tags in string on position



matak
06-01-2007, 05:57 PM
Actually i have an array of starting positions like this

EDIT: Array ( [0] => 2 ) Array ( [0] => 5 ) Array ( [0] => 8 )

and after 2 characters, all of the chars need to be bolded

How can i place html tags eg <b></b> to string based on that array


$string = "Textthatisnotbold";

$positions = array( 2, 5, 8);
$positionend = 2;

function place_tag($string, $positions, $positioned) {

//functiont to give THIS result

}


Te<b>xt</b>t<b>ha</b>tis<b>not</b>bold

Crack this one guyz, and you got beer from me :D

whizard
06-01-2007, 08:40 PM
Try this one out -

<?php
function place_tags($string,$positions,$positionend)
{
$count = count($positions);
$nextchar = 0;
for($i = 0;$i<$count;$i++)
{
$newstring .= substr($string,$nextchar,$positions[$i]-$nextchar);
$newstring .= "<strong>". substr($string,$positions[$i],$positionend) ."</strong>";
$nextchar = $positions[$i]+$positionend;
}
$newstring .= substr($string,$nextchar);
return $newstring;
}
$string = "Textthatisnotbold";
$positions = array(2,5,10);
$positionend = 2;
$formatted_string = place_tags($string,$positions,$positionend);
print $formatted_string;
?>

HTH,
Dan

printf
06-01-2007, 09:40 PM
Without putting to much thought into it...


<?php

function add_tags ( $str, $len, $pos, $tag )
{
$str = str_split ( $str );

$len -= 1;

foreach ( $pos AS $v )
{
$str[$v] = $tag[0] . $str[$v];
$str[$v+$len] .= $tag[1];
}

return join ( '', $str );
}

$len = 2;

$str = "Textthatisnotbold";

$pos = array ( 2, 5, 8 );

$tag = array ( '<b>', '</b>' );

echo add_tags ( $str, $len, $pos, $tag );

?>

matak
06-02-2007, 04:23 AM
Thank you guys very much, both of those functions show me a great path to solving my problem, as they are simple and work in order. I'll continue to study them a bit more tomorow.

You got your selfz a beer (or more) from me :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum