user3049006
user3049006

Reputation:

How to find a specific word in a string and add a character before the string in php?

I have a string This is a string and i want to add a character # before a word but i don't know how to do that in php.

I have tried this code:

$string = 'This is a string';

substr_replace($string, '#', stripos($string, 'a'), 0);

It is working fine but the problem is that if i want to add '#' before 'is' then it will give the following output.

Th#is is a string a string

I am looking for a function which can find a particular word and add a character before that word.

Upvotes: 0

Views: 279

Answers (3)

Markus Hofmann
Markus Hofmann

Reputation: 3447

Use preg_replace for this task. Also specify 1 for the limit param of this PHP function to limit the maximum possible replacements to 1.

Here is an example of how you might implement this function:

$string = 'This is a string and it is working fine';

$result = preg_replace('/\bis\b/i', '#$0', $string, 1);

In this case $result would contain the following:

This #is a string and it is working fine

The regex used ('/\bis\b/i') is made up of the following syntax:

// => The enclosing delimiters (before and after the pattern)

\b => Specifies a word boundary condition

/i => (optional) This is a pattern modifier that sets the pattern to case-insensitive (caseless)

/u => (optional - not included in example pattern) This is another pattern modifier that makes the string being treated as UTF-8. Use in case you have strings containing UTF-8 encoded characters.

A little side note about regex delimiters: Instead of slashes (/) you may also use other characters as delimiter like e.g. hash signs (#) and tildes (~). If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If it appears often inside the pattern, it's a good idea to choose another delimiter in order to increase readability. (Source: http://php.net/regexp.reference.delimiters)

Upvotes: 0

ALOK
ALOK

Reputation: 553

Yes you tried right just use strrpos() in place of stripos().

$newstr=substr_replace($temp, '#', strrpos($temp, 'is'),0);

refer http://www.w3schools.com/php/func_string_strpos.asp for difference and to learn other strpos() function.

Upvotes: 0

deceze
deceze

Reputation: 522175

$string = preg_replace('/\bis\b/i', '#$0', $string);

\b signifies a word boundary, the /i makes the whole thing case insensitive (optional, but probably a good idea). Learn more about regular expressions here so you can alter this as needed.

Upvotes: 1

Related Questions