Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 72
  • Last Modified:

Php string function

i have a string which has 7 letters

I want to change the first two letters of this strings if it's first two letter is "st"

How can do it with php?
0
Braveheartli
Asked:
Braveheartli
1 Solution
 
Ryan ChongCommented:
try this:
<?php

$yourStr = "stllo12";
$findStr = "st";
$replaceStr = "bo";

if (substr($yourStr,0,2) == $findStr) {
    $yourStr = str_replace($findStr,$replaceStr,$yourStr);
}

echo substr($yourStr,0,2)." ".$findStr." ".$yourStr;

?>

Open in new window

0
 
BraveheartliMarketingAuthor Commented:
thank you
0
 
Julian HansenCommented:
Alternative

var $result = preg_replace('/^[s|S][t|T]/', 'bo', $str);

Will match any combination of case for 'st' but will replace with lower case.
Test case
<?php
$tests = array (
  "street",
  "sTreet",
  "treet",
  "sstreet",
  "STREET",
  "astreet",
  "Street",
  "avast",
  "harvester"
);
foreach($tests as $t) {
	echo "Original: [{$t}] - Replace [" . preg_replace('/^[s|S][t|T]/', 'bo', $t) . "]<br/>";
}

Open in new window

Result
Original: [street] - Replace [boreet]
Original: [sTreet] - Replace [boreet]
Original: [treet] - Replace [treet]
Original: [sstreet] - Replace [sstreet]
Original: [STREET] - Replace [boREET]
Original: [astreet] - Replace [astreet]
Original: [Street] - Replace [boreet]
Original: [avast] - Replace [avast]
Original: [harvester] - Replace [harvester]

Open in new window

1
 
Ray PaseurCommented:
This may not be part of the question, but it's worth knowing.

Search this page for "English ordinal suffix"
0
 
BraveheartliMarketingAuthor Commented:
Thank you Ray,
You are the man.
You are great, Sage, Genius.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now