Please show your love and support by sharing this post. It was published 01 Jul, 2018 (and was last revised 03 Jun, 2021). Now with that result, you can simply use implode() to join the string back using the replace-with value like so:Įcho implode($replaceWith, explode($findStr, $str, 2)) output: Array ( => "" => "bar foobaz fooqux") With that knowledge, consider the example below: For example, if limit is set to 2, then the returned array will contain ONE matching element with the last element containing the rest of the string. When a positive value is supplied as the $limit, the returned array will contain a maximum of $limit elements with the last element containing the rest of string. Consider the following (complete) syntax of the explode() function: ![]() Using the third argument to the explode() function, you can ensure you only split the string once at the first match. $str = substr_replace($str, $replaceWith, $pos, strlen($findStr)) the starting offset of the match and the length of the portion of string which is to be replaced) can be used to ensure only the whole string (that's of concern to us) is replaced, and only once. The last two parameters of the substr_replace() function (i.e. Substr_replace($string, $replacement, $startOffset, $length) The substr_replace() function has the following syntax: If an array of patterns is provided then to replace the first match of each pattern you can do the following:Įcho preg_replace(, $replaceWith, $str, 1) The first argument to the preg_replace() function can either be a string pattern or an array of string patterns. Replacing First Match From Multiple Patterns Using preg_replace(): For example, to limit it to only the first match, you could do the following:Įcho preg_replace('/'. The fourth argument to the preg_replace() function can be used to limit the number of times the match is replaced. ![]() The idea is to divide the string into two strings: one that. Therefore, it may not be helpful in restricting the number of replacements to only the first find. You can replace the first occurrence of a substring using the implode() and explode() functions. In this article, we've handpicked a few that we believe are good for the job.įor all the examples in this article, we'll be using the following string to replace the first occurrence of foo:Ĭan I Use str_replace() to Replace Only the First Match?īy default, PHP's str_replace(), replaces all occurrences of a match an optional fourth argument to the function gives the number of replacements performed, and does not help in limiting the number of replacements that will be made. There are several ways in PHP that you could use to replace only the first match in a string.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |