Reputation:
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
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
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