0

So I have str_replace which searches a string for "and" and replaces it with & However if there is a word which contains the letters "and" for example, "Howland" it will replace it with Howl&.

How can I make it so that it only searches for the word and.

This is my function I have setup:

function add_ampersand( $string ) {
    $string = str_replace( 'and', '&', $string );

    return $string;
}

I must note that this function is being used in a URL so the "and" will contain "-" next to either side of it, which then gets converted into spaces.

karthikr
  • 97,368
  • 26
  • 197
  • 188
Sygon
  • 222
  • 5
  • 15

3 Answers3

5

You could use

function add_ampersand( $string ) {
    $string = preg_replace( '/\band\b/', '&', $string );

    return $string;
}

or

function add_ampersand( $string ) {
    $string = str_replace( ' and ', ' & ', $string );

    return $string;
}

The first one is better in the case "and" is next to the end of the string or next to a special character such as ', , or ..

PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
  • This did the trick, I had already tried adding the space before but I guess I forgot to add the space either side of the & as well. Thanks! – Sygon Aug 29 '13 at 14:10
0

Try this

function add_ampersand( $string ) {
    $string = str_replace( ' and ', ' & ', $string );
    return $string;
}
Padmanathan J
  • 4,614
  • 5
  • 37
  • 75
0

If I understand you, you have strings like this: "-and" or "and-" or "-and-". The easiest way of replacing it to &amp is this:

function add_ampersand( $string ) {
    $string = str_replace( '-and', '-&', $string );
    $string = str_replace( 'and-', '&-', $string );
    $string = str_replace( '-and-', '-&-', $string );

    return $string;
}
Norbert
  • 302
  • 1
  • 9
  • 19