vdegenne
vdegenne

Reputation: 13270

replacing occurences of a word with another on the first line of a text in PHP

let say i have a text :

this line is the first line of this text called %title%

this line is the second one

the third line, %title% shouldn't be replaced

...

last line

now I want to use PHP so the text becomes :

this line is the first line of this text called MY_TITLE

this line is the second one

the third line, %title% shouldn't be replaced

...

last line

NOTICE the %title% on the third line also

what would be the best (fastest) way to do that ?

Upvotes: 0

Views: 70

Answers (3)

Robert
Robert

Reputation: 20286

You can use preg_replace() it's just one line of code ;)

$str = "this line is the first line of this text called %title%\n
this line is the second one\n
the third line, %title% shouldn't be replaced\n
last line";

echo preg_replace('/%title%$/m','MY_TITLE',$str);

Explanation of regex:

  • /%title% means %title%
  • $ means end of line
  • m makes the beginning of input (^) and end of input ($) codes also catch beginning and end of line respectively

Output:

this line is the first line of this text called MY_TITLE
this line is the second one the third line, %title% shouldn't be replaced
last line

Upvotes: 3

Eugen Rieck
Eugen Rieck

Reputation: 65274

There are two approaches:

  • If you are sure, that the replacement has to be done exactly one time (i.e. the placeholder will allways be in the first line, and allways only onec), you can use $result=str_replace('%title%','MY_TITLE',$input,1)

  • If this is not guaranteed, you need to separate the first line:

.

$pos=strpos($input,"\n");
if (!$pos) $result=$input;
else $result=str_replace('%title%','MY_TITLE',substr($input,0,$pos)).substr($input,$pos);

Upvotes: 4

Martin Perry
Martin Perry

Reputation: 9527

You can load only first line to variable, than do str_ireplace and then put first line + rest of the file back together.

$data = explode("\n", $string);
$data[0] = str_ireplace("%title%", "TITLE", $data[0]);    
$string = implode("\n", $data);

Its not the most efficient way imho, but suitable and fast to code.

Upvotes: 4

Related Questions