Nicole
Nicole

Reputation: 23

Easy PHP Replace

I want the first word of the string to be surrounded by tags. Insted with my code all the words gets surrounded by it.

The code is for a wordpress so the_title is the title of the post. Eg. Hello World. I want it to be <span>Hello </span>World.

<?php
$string = the_title('', '', false);
$pattern = '^(\S+?)(?:\s|$)^';
$replacement = '<span>$1</span>';
$string = preg_replace($pattern, $replacement, $string);
?>

            <h2><a href="<?php the_permalink(); ?>"><?=$string?></a></h2> 

Sorry for my bad english :)

MY SOLUTION:

<?php
$string = the_title('', '', false);
$pattern = '/\S+/';
$replacement = '<span>$0</span>';
$string = preg_replace($pattern, $replacement, $string, 1);
?>

            <h2><a href="<?php the_permalink(); ?>"><?=$string?></a></h2> 

Upvotes: 2

Views: 204

Answers (5)

codaddict
codaddict

Reputation: 455302

Try limiting the number of replacements to 1 by passing 1 as the 4th argument to preg_replace as:

$string = preg_replace($pattern, $replacement, $string,1);
                                                      ^^

A better regex to find words would be using word boundaries:

$pattern = '/\b(\w+)\b/';

but this way you'll have to restrict the replacement to 1 again.

Alternatively you can just match the first word as:

$pattern = '/^\W*\b(\w+)\b/';

and just use preg_replace without limiting number of replacements.

NOTE: \w = [a-zA-Z0-9_] if your word is allowed to have other characters, change suitably. If you consider any non-whitespace as a word character you can use \S.

Upvotes: 1

atx
atx

Reputation: 5079

Use something like the following:

$string = "Hello World";
$val = explode(" ", $string);
$replacement = '<span>'.$val[0].' </span>';
for ($i=1; $i < count($val); $i++) {
    $replacement .= $val[$i];
}
echo "$replacement";

Upvotes: 1

Cyclone
Cyclone

Reputation: 18295

$string = '"' . substr($string, 0, strpos($string, ' ')) . '"'; ought to do the trick!

Upvotes: 0

netcoder
netcoder

Reputation: 67735

PCRE is not necessary in this case. You could do the same with a simple substr/strpos combination (which should, although minimally, be faster):

$str = 'Hello World';

$endPos = strpos($str, ' ')+1;
$str = '<span>'.substr($str, 0, $endPos).'</span>'.
       substr($str, $endPos);
echo $str;

If you really want to go with the PCRE way, you can do:

$str = preg_replace('/^([^\s]+\s)/', '<span>\1</span>', $str);

The statement does not require a $limit, because the pattern starts with a ^ (beginning of string), which is not a delimiter, unlike yours.

Upvotes: 0

user432219
user432219

Reputation:

You have to update the pattern and the replacement like this (this ignores first whitespaces at the beginning):

<?php

$string = the_title('', '', false);
$pattern = "^(\\s*)(\\S+)(\\s*)(.*?)$";
$replacement = '<span>$2</span>';
$string = preg_replace($pattern, $replacement, $string);

Upvotes: 0

Related Questions