# Solved: STR_REPLACE: Once!



## MMJ (Oct 15, 2006)

I want to do a STR_REPLACE only once but there seems to be no way to do so.

PREG_REPLACE is supposed to have a limit but I couldn't get it to work. 

Any help?

Thanks.


----------



## brendandonhu (Jul 8, 2002)

http://us2.php.net/manual/en/function.str-replace.php#67979


----------



## MMJ (Oct 15, 2006)

Okay, thats great, thanks!

But how can I tell it to remove from the end not from the beginning?

Thanks.


----------



## brendandonhu (Jul 8, 2002)

Write a regular expression.


----------



## MMJ (Oct 15, 2006)

brendandonhu said:


> Write a regular expression.


Didn't figure it was worth it.  

Wrote this up instead:

```
<?php
	$string_len = strlen($string); //Get the length of the string
	$string_len2 = strlen("$string2"); //Get the length of what we want to remove
	$min = $string_len - $string_len2; //Subtract them
	echo substr($string, 0, $min); //Get the result.
?>
```
It took some time though.


----------



## brendandonhu (Jul 8, 2002)

This does the same thing:

```
<?php
	echo substr($string, 0, -strlen($string2));
?>
```
Of course it's not going to give you the results you want if $string doesn't end with $string2. 
This might be more like what you're looking for

```
<?php
	echo preg_replace("/$string2$/", '', $string)
?>
```


----------



## MMJ (Oct 15, 2006)

I get $string2 from the end of $string; using some other code I wrote.


----------



## brendandonhu (Jul 8, 2002)

Ok, then the first one should work fine


----------



## MMJ (Oct 15, 2006)

Yup, thanks for your help. 

Marking this one solved.


----------

