Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Depending on your common search string and your version of PCRE, either <code>preg_replace</code> or <code>strrpos</code> will probably fare best:</p> <h2>Functions</h2> <pre><code>function usingExplode($string, $replacement) { $pieces = explode('_', $string); array_pop($pieces); return implode('_', array_merge($pieces, array($replacement))); } function usingStrrpos($string, $replacement) { return substr($string, 0, strrpos($string, '_') + 1) . $replacement; } function usingPreg($string, $replacement) { return preg_replace('/_[^_]*$/', '_' . $replacement, $string); } </code></pre> <h2>Test harness</h2> <pre><code>function speedTest($function, $string, $count = 100000) { $start = microtime(true); for ($i = 0; $i &lt; $count; $i++) { $function($string, 'replacement'); } $end = microtime(true); printf('%-12s: %01.2fs%s', $function, $end - $start, PHP_EOL); } $tests = array('a_b_c', 'abcdefghijklmnopqrstuvwxy_z', 'a_bcdefghijklmnopqrstuvwxyz', 'a_b_c_d_e_f_g_h_i_j_k_l_m_n_o_p_q_r_s_t_u_v_w_x_y_z'); foreach ($tests as $test) { echo $test . ':' . PHP_EOL; speedTest('usingExplode', $test); speedTest('usingStrrpos', $test); speedTest('usingPreg', $test); echo PHP_EOL; } </code></pre> <h2>Results</h2> <pre><code>a_b_c: usingExplode: 0.64s usingStrrpos: 0.34s usingPreg : 0.33s abcdefghijklmnopqrstuvwxy_z: usingExplode: 0.61s usingStrrpos: 0.32s usingPreg : 0.32s a_bcdefghijklmnopqrstuvwxyz: usingExplode: 0.60s usingStrrpos: 0.32s usingPreg : 0.32s a_b_c_d_e_f_g_h_i_j_k_l_m_n_o_p_q_r_s_t_u_v_w_x_y_z: usingExplode: 1.39s usingStrrpos: 0.32s usingPreg : 0.71s </code></pre> <p>Note that (at least on my set-up with PHP 5.4.0), <code>preg_replace</code> gives <code>strrpos</code> a run for its money until there are a large number of underscores preceding the last one.</p> <p><strong>EDIT</strong>: I plugged <a href="https://stackoverflow.com/a/10236047/283078">bfrohs's regex</a> into the suite and unless the underscore to replace is near the beginning of the string, it doesn't do very well:</p> <pre><code>a_b_c: usingPreg2: 0.40s abcdefghijklmnopqrstuvwxy_z: usingPreg2: 1.91s a_bcdefghijklmnopqrstuvwxyz: usingPreg2: 0.38s a_b_c_d_e_f_g_h_i_j_k_l_m_n_o_p_q_r_s_t_u_v_w_x_y_z: usingPreg2: 1.04s </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload