Skip to content
Advertisement

PHP add html tag to first word

Trying to add HTML tags around the first word in each new line in WooCommerce short description and validate that the file exist. If it exist it will output a link.

I tried this:

$string = $short_description;
$keys = array('a1', 'a2', 'a3');
$patterns = array();
foreach($keys as $key)
    $patterns[] = '/b('.$key.')b/i';

echo preg_replace($patterns, '<a href="https://www.example.com/media/'.$product->get_sku().'/'.$product->get_sku().'$0.pdf">$0</a>', $string);

$url = preg_replace($patterns,  'https://www.example.com/media/' .$product->get_sku(). '/' .$product->get_sku(). '$0.pdf', $string); 

$handle = @fopen($url,'r'); 
if($handle !== false){ ?>
<?php echo preg_replace($patterns, '<li><a href="https://www.example.com/media/'.$product->get_sku().'/'.$product->get_sku().'$0.pdf">$0</a></li>', $string);?>
<?php } else {?>
<?php echo preg_replace($patterns, '<li>$0</li>', $string);?>

This is as close I could get, the limitation is that you need to add all words that needs to be changed (will be total 200+) and also the validation $url is not working as it echos the $string aswell.

So how can I either get the $url correct or is there a better way to wrap html tags to the first word on each new line?

Advertisement

Answer

Got it working with:

$s = strip_tags($short_description, '<br>');
$rows = explode( "n", $s );
foreach( $rows as $r ){
echo preg_replace('/^([^ ]*)/', '$1', $r);
}

and then with

if is_readable

to output link or not

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement