Question

I know the $a variable with the tag is not properly formatted, however that's irrelevant to the issue.

The issue is that strpos is looking for a forward slash, /, in the value of each key in the array, but it is not printing.

$a = '<a target="" href="/test/url">test';
$a_expanded = explode("\"", $a);
echo print_r($a_expanded);
foreach($a_expanded as $num => $aspect) {
  echo $aspect;
  if ($contains_path = strpos($aspect, '/')) {
    echo $a_expanded[$num];
  }
}

It echos the array and each aspect, but will not echo the string with the forward slashes when found by strpos.

Was it helpful?

Solution 3

strpos() could either return FALSE, 0, or a non-zero value.

  • If the needle occurs at the beginning of the haystack, strpos() returns 0.
  • If it occurs elsewhere, it returns the respective position of the needle in the haystack.
  • If needle wasn't found in the haystack, strpos() returns boolean FALSE.

I wasn't checking for strict equality, so the if statement always returned a falsey value, causing my code to not work.

if ($contains_path = strpos($aspect, '/'))

To fix the issue, you could use !==, which compares the type and value:

if ($contains_path = (strpos($aspect, '/') !== FALSE))

For more information, check the following links:

OTHER TIPS

if ($contains_path = strpos($aspect, '/'))

should be

$contains_path = strpos($aspect, '/');
if ($contains_path !== false)

as strpos will return 0 when the string directly starts with a / (as it does, in your case). If strpos has no match, it returns false.

if (0) and if (false) are the same. So you need to do strict comparison (=== or !==) here.

The position of found string might be 0 which is counted as false, you need to compare as ===

if (false !== $contains_path = strpos($aspect, '/')) {
   echo $a_expanded[$num];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top