Jump to content

[SOLVED] Replacing string within string if it appears at the start


Nokki

Recommended Posts

Hi there,

 

I am looking for some help with replacing a string within a string if the following condition is true:

 

Example String:

 

$string = "8250; this is a test";

 

The thing is: The number always changes so I can't just do a str_replace

 

So what I am looking for is some function like

 

IF the beginning of the string is

 

NUMBERNUMBERNUMBERNUMBER;

 

THEN replace it with &#NNNN;

 

It's important that the function does not replace it when it's in the middle - only if the first 5 chars are NNNN; then we add a &#

 

 

Thanks for reading

 

This forum seems to be a great place to ask questions cause people actually answer :)

 

Thanks again!

 

 

Should be simple enough..

 

<?php

$string = '8250; this is a test';

$search = substr($string, 0, 4);

echo "search is $search<br>";

if (is_numeric($search)) {
$replace = '&#'.$search;
$string = str_replace($search,$replace,$string);
}

echo "string is $string<br>";

?>

Looks nearly perfect. However (correct me if I am wrong) it does not take the ; character into the check, so if the string would be "1000 birds fly over the sea" it would incorrectly make it &#1000 birds fly over the sea which could cause more harm than it does good :)

 

Do you maybe have an idea how to take the ; char into account?

 

Thanks for your reply!

 

 

Sorry, I edited that after you replied it seems.. try this as it works on my server..

 

<?php

 

$string = '8250; this is a test';

 

$search = substr($string, 0, 4);

 

echo "search is $search<br>";

 

if (is_numeric($search)) {

$replace = '&#'.$search;

$string = str_replace($search,$replace,$string);

}

 

echo "string is $string<br>";

 

?>

 

Thanks for that - I changed one more thing so the ; character is taken into account.

 

<?php

$string = '8250; this is a test';

$search = substr($string, 0, 4);

echo "search is $search<br>";

if (is_numeric($search)) {
$replace = '&#38;#'.$search;
$string = str_replace($search.";",$replace,$string);
}

echo "string is $string<br>";

?>

 

I basically just added .";"

 

to your

 

$string = str_replace($search.";",$replace,$string);

 

and now everything is perfect and it only replaces if there is a ; after the numbers :)

 

Thanks for your help!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.