How to find string position php - php

I want to get the position of 'ja' in each of the words in $string, but its not working. what am i doing wrong?
<?php
$offset = 0;
$find = 'ja';
$find_length = strlen($find);
$string = 'jasim jasmin jassir';
while ($string_position = strpos($string, $find, $offer)) {
echo $find.' found at '.$string_position.'<br>';
$offset = $string_position + $find_length;
}
?>

Change the variable name to $offset
strpos may return 0 and while will treat it as false
So replace your while statement with:
while (($string_position = strpos($string, $find, $offset)) !== false) {

<?php
// stack overflow area
$offset = 0;
$find = 'ja';
$find_length = strlen($find);
$string = 'jasim jasmin jassir';
if (strpos($string, $find) === false) {
echo "not found";
}
else {
while (strpos($string, $find, $offset) !== false) {
$string_position = strpos($string, $find, $offset);
echo $find.' found at '.$string_position.'<br>';
$offset = $string_position + $find_length;
}
}
?>
Little workaround, but it apparently works.
Output:
ja found at 0
ja found at 6
ja found at 13

try changing offest
<?php
$offset = 1;
$find = 'ja';
$find_length = strlen($find);
$string = 'jasim jasmin jassir';
while ($string_position = strpos($string, $find, $offset)) {
echo $find.' found at '.$string_position.'<br>';
$offset = $string_position + $find_length;
}
?>
// output :- ja found at 6
ja found at 13
if you don't want to change offset use
$string = ' jasim jasmin jassir'; (without space not be jasim it's 'jasim )
then it will output 3
ja found at 1
ja found at 7
ja found at 14
OR try to change your condition check
while (($string_position = strpos($string, $find, $offset)) !== false) {

Probably you should code this way to find string positions
$positions = array();
$offset = -1;
while (($pos = strpos($string, $find, $offset+1)) !== false) {
$positions[] = $offset;
}
$result = implode(', ', $positions);
print this result

Related

echo partially hidden (IPV4 or IPV6) ip in a table

I have a table where a variable in a row containing IP information is being echoed. I think there's an issue with my if statement, because if I use the following then I can get the variable to echo:
echo $row['log_ip'] = substr_replace ($row['log_ip'], $ipv4replacement, stripos ($row['log_ip'], $ipv4needle, $offset = 2));
My current code:
$ipv6needle = ':';
$ipv4needle = '.';
$ipv4replacement = '.***.***.***';
$ipv6replacement = ':****:****:****:****:****:****:****';
if (strpos($row['log_ip'], ':') !== FALSE) {
echo $row['log_ip'] = substr_replace ($row['log_ip'], $ipv4replacement, stripos ($row['log_ip'], $ipv4needle, $offset = 2));
else
echo $row['log_ip'] = substr_replace ($row['log_ip'], $ipv6replacement, stripos ($row['log_ip'], $ipv6needle, $offset = 2)); }
Your code is full of weird assignments, I don't know what you want to achieve with them, but here's a corrected and refactored code.
<?php
$offset = 2;
if (strpos($row["log_ip"], ":") !== false) {
$needle = ".";
$replacement = ".***.***.***";
}
else {
$needle = ":";
$replacement = ":****:****:****:****:****:****:****";
}
$row["log_ip"] = substr_replace($row["log_ip"], $replacement, stripos($row["log_ip"], $needle, $offset));
echo $row["log_ip"];
Answer to the question in the comment:
<?php
function mask_ip_address($ip_address) {
if (strpos($ip_address, ".") !== false) {
$parts = explode(".", $ip_address);
return $parts[0] . str_repeat(".***", 3);
}
$parts = explode(":", $ip_address);
return $parts[0] . str_repeat(":****", 7);
}
function mask_ip_address_test($ip_address, $expected) {
assert($expected === mask_ip_address($ip_address));
}
mask_ip_address_test("17.0.0.1", "17.***.***.***");
mask_ip_address_test("fe80::200:5aee:feaa:20a2", "fe80:****:****:****:****:****:****:****");

strpos result 0 stops while loop

i need to find the all positions of a particular character in a string. I am using the following code
$pos = 0;
$positions = array();
while( $pos = strpos($haystack,$needle,$pos){
$positions[] = $pos;
$pos = $pos+1;
}
the problem with this code is that when the needle is at location 1,its returns 1 and so doesn't enter the loop.
So i tried the following
$pos = 0;
$positions = array();
while( ($pos = strpos($haystack,$needle,$pos) || (strpos($haystack,$needle,$pos)=== 0){
$positions[] = $pos;
$pos = $pos+1;
}
and,
$pos = 0;
$positions = array();
while( ($pos = strpos($haystack,$needle,$pos) || (strpos($haystack,$needle,$pos) != false){
$positions[] = $pos;
$pos = $pos+1;
}
But nothing seems to be working. Is there any other way.
The two alternative i tried give me
Allowed memory size of 268435456 bytes exhausted
which i think has more to do with programming error than memory issue.
Plz help.
You need to use !== instead of != because zero is considered false so you need to compare by type as well:
while($pos = (strpos($haystack,$needle,$pos) !== false){
$positions[] = $pos;
$pos++;
}
Edit
See the working version of your code from the comment:
$positions = array();
while( ($pos = strpos('lowly','l',$pos)) !== false){
$positions[] = $pos;
$pos++;
}
print_r($positions);
See it working here.
Use this code..
$start = 0;
while ($pos = strpos($string, ',', $start) !== FALSE) {
$count++;
$start = $pos + 1;
}

How to remove specific html tags from a line in string?

$find = '{<p>something</p>}';
$str1 = "<p>{<p>something</p>}</p>\r\ntext<p>something else</p>";
// or
$str2 = "<p>something</p>\r\n{<p>something</p>}aa<p>t</p>\r\ntext<p>something else</p>";
Basically, $find can be anywhere in the string. New lines delimiter is "\r\n".
I need to find $find in the $str and remove specific html tags around $find in that specific string line. No tags should be removed from $find.
Expected output would be
// For $str1
$str1 = "{<p>something</p>}\r\ntext<p>something else</p>";
// For $str2
$str2 = "<p>something</p>\r\n{<p>something</p>}aat\r\ntext<p>something else</p>";
The string might be very long, so no regex solutions please.
What I have figured out:
$pos = strpos($str, $find);
if ($pos !== false) {
$contentLength = strlen($str);
$lineStart = (int)strrpos($str, "\r\n", -$contentLength+$pos); // cast false to 0 (start of string)
$lineEnd = strpos($str, "\r\n", $pos);
if ($lineEnd === false)
$lineEnd = strlen($str);
$lineLength = $lineEnd-$lineStart;
if ($lineLength < 0)
return;
var_dump(substr($str, $lineStart, $lineLength));
}
Which dumps that specific line in the string.
My final solution:
function replace($find, $str, $replace) {
$pos = strpos($str, $find);
if ($pos !== false) {
$delim = "\r\n";
$contentLength = strlen($str);
$lineStart = strrpos($str, $delim, -$contentLength+$pos);
if ($lineStart === false)
$lineStart = 0;
else
$lineStart += strlen($delim);
$lineEnd = strpos($str, $delim, $pos);
if ($lineEnd === false)
$lineEnd = strlen($str);
$lineLength = $lineEnd - $lineStart;
$line = substr($str, $lineStart, $lineLength);
$posLine = strpos($line, $find); // Where $find starts
$findLength = strlen($find);
$line = substr_replace($line, '', $posLine, $findLength); // Remove $find from $line
$begin = replaceTags(substr($line, 0, $posLine));
$end = replaceTags(substr($line, $posLine));
return substr_replace($str, $begin.$replace.$end, $lineStart, $lineLength);
}
}
function replaceTags($str) {
return str_replace(array('<p>', '</p>'), '', $str);
}
echo replace($find, $str, $replace);

PHP Find all occurrences of a substring in a string

I need to parse an HTML document and to find all occurrences of string asdf in it.
I currently have the HTML loaded into a string variable. I would just like the character position so I can loop through the list to return some data after the string.
The strpos function only returns the first occurrence. How about returning all of them?
Without using regex, something like this should work for returning the string positions:
$html = "dddasdfdddasdffff";
$needle = "asdf";
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
// Displays 3 and 10
foreach ($positions as $value) {
echo $value ."<br />";
}
You can call the strpos function repeatedly until a match is not found. You must specify the offset parameter.
Note: in the following example, the search continues from the next character instead of from the end of previous match. According to this function, aaaa contains three occurrences of the substring aa, not two.
function strpos_all($haystack, $needle) {
$offset = 0;
$allpos = array();
while (($pos = strpos($haystack, $needle, $offset)) !== FALSE) {
$offset = $pos + 1;
$allpos[] = $pos;
}
return $allpos;
}
print_r(strpos_all("aaa bbb aaa bbb aaa bbb", "aa"));
Output:
Array
(
[0] => 0
[1] => 1
[2] => 8
[3] => 9
[4] => 16
[5] => 17
)
Its better to use substr_count . Check out on php.net
function getocurence($chaine,$rechercher)
{
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($chaine, $rechercher, $lastPos))!== false)
{
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($rechercher);
}
return $positions;
}
This can be done using strpos() function. The following code is implemented using for loop. This code is quite simple and pretty straight forward.
<?php
$str_test = "Hello World! welcome to php";
$count = 0;
$find = "o";
$positions = array();
for($i = 0; $i<strlen($str_test); $i++)
{
$pos = strpos($str_test, $find, $count);
if($pos == $count){
$positions[] = $pos;
}
$count++;
}
foreach ($positions as $value) {
echo '<br/>' . $value . "<br />";
}
?>
Use preg_match_all to find all occurrences.
preg_match_all('/(\$[a-z]+)/i', $str, $matches);
For further reference check this link.
Salman A has a good answer, but remember to make your code multibyte-safe. To get correct positions with UTF-8, use mb_strpos instead of strpos:
function strpos_all($haystack, $needle) {
$offset = 0;
$allpos = array();
while (($pos = mb_strpos($haystack, $needle, $offset)) !== FALSE) {
$offset = $pos + 1;
$allpos[] = $pos;
}
return $allpos;
}
print_r(strpos_all("aaa bbb aaa bbb aaa bbb", "aa"));
Another solution is to use explode():
public static function allSubStrPos($str, $del)
{
$searchArray = explode($del, $str);
unset($searchArray[count($searchArray) - 1]);
$positionsArray = [];
$index = 0;
foreach ($searchArray as $i => $s) {
array_push($positionsArray, strlen($s) + $index);
$index += strlen($s) + strlen($del);
}
return $positionsArray;
}
Simple strpos_all() function.
function strpos_all($haystack, $needle_regex)
{
preg_match_all('/' . $needle_regex . '/', $haystack, $matches, PREG_OFFSET_CAPTURE);
return array_map(function ($v) {
return $v[1];
}, $matches[0]);
}
Usage:
Simple string as needle.
$html = "dddasdfdddasdffff";
$needle = "asdf";
$all_positions = strpos_all($html, $needle);
var_dump($all_positions);
Output:
array(2) {
[0]=>
int(3)
[1]=>
int(10)
}
Or with regex as needle.
$html = "dddasdfdddasdffff";
$needle = "[d]{3}";
$all_positions = strpos_all($html, $needle);
var_dump($all_positions);
Output:
array(2) {
[0]=>
int(0)
[1]=>
int(7)
}
<?php
$mainString = "dddjmnpfdddjmnpffff";
$needle = "jmnp";
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
// Displays 3 and 10
foreach ($positions as $value) {
echo $value ."<br />";
}
?>

How to find position of a character in a string in PHP

How to find positions of a character in a string or sentence in php
$char = 'i';
$string = 'elvis williams';
$result = '3rd ,7th and 10th'.
I tried strpos..but no use..
This will give you the position of $char in $string:
$pos = strpos($string, $char);
If you want the position of all occurences of $char in string:
$positions = array();
$pos = -1;
while (($pos = strpos($string, $char, $pos+1)) !== false) {
$positions[] = $pos;
}
$result = implode(', ', $positions);
print_r($result);
Test it here: http://codepad.viper-7.com/yssEK3

Categories