• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 243
  • Last Modified:

Q about substr

hi

$pharse1 is a substring of $text,
how can I get the the 12 cases before phrase1?
(there is only one phrase1 in $text)

regards
0
uk1900
Asked:
uk1900
  • 4
  • 3
  • 2
2 Solutions
 
khaledfCommented:
your question is not clear enough.
can you explain this question by example?
"how can I get the the 12 cases before phrase1?"
0
 
uk1900Author Commented:
lets say
$text =  "abcdefghijklmnopqrstuvqxyz";
$phrase1 = "mnopq";

how can I get the 12 letter before "mnopq" in $text;
0
 
ddrudikCommented:
For the 12 letters prior:
<?php
$phrase1="test";
$text="43210987654321test123456";
echo substr($text,strpos($text,$phrase1)-12,12);
?>

Open in new window

0
Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

 
ddrudikCommented:
String functions would be preferred over regex functions, but here's another one of the ways to match these 12 characters:
<?php
$phrase1="test";
$text="43210987654321test123456";
preg_match("/.{12}(?=$phrase1)/",$text,$match);
echo $match[0];
?>

Open in new window

0
 
uk1900Author Commented:
both works,
which one is has the best speed performence when it comes to 100s of loops?
0
 
khaledfCommented:
to check which one is best for performance, put the code between these 2 php blocks

<?  $time = microtime(true);  ?>


// YOUR CODE HERE

<?  
$time2 = microtime(true);  
$gentime = $time2 - $time;
echo "$gentime";
?>

and see which one is faster
0
 
ddrudikCommented:
uk1900, it would be expected that string functions (substr etc.) are always faster than regex functions, regex functions are best used when string functions are not available for the specific task.  I just thought I would show another way to do it.
0
 
uk1900Author Commented:
thank you for your help
0
 
ddrudikCommented:
Thanks for the question and the points.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now