740

How to change first occurrence of word in a string

<h3>Question</h3>

How do I do to change the first occurrence of a word in a string?

Example:

$a = "Yo! **Hello** this is the first word of Hello in this sentence";

to

$b = "Yo! **Welcome** this is the first word of Hello in this sentence";
<h3>Answer1:</h3>

This works, although a bit inefficient:

$a = "Yo! **Hello** this is the first word of Hello in this sentence"; $a = preg_replace('/Hello/', 'Welcome', $a, 1);

The other popular answer:

$b = str_replace('Hello', 'Welcome', $a, 1);

does not work. The fourth argument of str_replace should be a variable, which is passed by reference and str_replace will set it to the <em>number of replacements made</em>.

A better solution would be to extract two sub-strings from the input string:

<ol><li>Sub-string before the first occurrence of Hello, call it $s1</li> <li>Sub-string after the first occurrence of Hello, call it $s2</li> </ol>

One can use the strpos to get the position.

Result is $s1.'Welcome'.$s2


<h3>Answer2:</h3>

Just use substr twice with strpos.

$a = "Yo! **Hello** this is the first word of Hello in this sentence"; $search = "Hello"; $replacement = "Welcome"; $b = substr( $a, 0, strpos( $a, $search)) . $replacement . substr( $a, strpos( $a, $search) + strlen( $search));

Demo


<h3>Answer3:</h3>

This is the best for compactness and performances:

if(($offset=strpos($string,$replaced))!==false){ $string=substr_replace($replaced,$replacer,$offset,strlen($replaced)); }

Replace only the first occurrence without the overload of the regular expressions


<h3>Answer4:</h3>

Use substr_replace().


<h3>Answer5:</h3>

Use str_replace('Hello','Welcome',$a,1);


<h3>Answer6:</h3>

Build It:

function str_replace_first($search, $replace, $source) { $explode = explode( $search, $source ); $shift = array_shift( $explode ); $implode = implode( $search, $explode ); return $shift.$replace.$implode; }

Call it:

$msg = "Yo! **Hello** this is the first word of Hello in this sentence"; echo str_replace_first( 'Hello', 'Welcome', $msg );

Try It:

http://sandbox.onlinephpfunctions.com/code/399ec70333832423c79d36a42032124d5c296d27

来源:https://stackoverflow.com/questions/8272108/how-to-change-first-occurrence-of-word-in-a-string

Recommend

  • ready to use uint route constraint?
  • how to add hooks after bundle update
  • Find first null in binary tree with limited memory
  • Timeouting a while loop in Linux shell script
  • Shift operators in PL/SQL
  • overwrite nuget packages in feed on visual studio team services
  • Java making Connect Four game panel
  • How do I click on a Cell of a DataGridView programmatically?
  • summarize data from csv using R
  • Master makefile which runs make files in subdirectories
  • get value from xml with r by attribute
  • Java: How to refer to subclass's static variable in abstract class?
  • iOS Today Extension created as .app rather than .appex
  • Find string between two substrings AND between string and the end of file
  • Redmine can't generate secret token
  • Get an image from the video
  • Parallelization via JDBC - Pyspark - How does parallelization work using JDBC?
  • plot dirac function in matlab
  • Unable to connect to Azure MySQL Database through Azure Function - C#
  • Tensorflow crash using tf.train.Saver() with GPU
  • How to get a time and Date Separately?
  • JQuery Mobile Ajax Navigation in Single-Page Template
  • How to add html image in to velocity template file to send email?
  • Julia 1.0 UndefVarError - Scope of Variable
  • How to load dynamic images in custom ListView
  • Set SelectedIndex of ListView in FlipView_SelectionChanged event
  • How to use Flask's render_template from an ajax POST form submit
  • How to merge objects within array based on attribute
  • concise way of flattening multiindex columns
  • Google Spreadsheet Script to Blink a range of Cells
  • Error handeling in antlr 3.0
  • how to run ejabberd with Erlang on Heroku?
  • Android: Unable to detect vertical plane
  • Debug `Unexpected end of JSON input Error` on content script
  • Bad automatic Triangulation with Mayavi for coloring a surface known only by its corner
  • Apple Mach-O Linker error (“duplicate symbol”)
  • Using Service Component Runtime
  • Angular FormGroup won't update it's value immediately after patchValue or setValue
  • WPF custom control and direct content support
  • How to handle a codeigniter PDF generator