I want to find the best way to calculate the point in the perimeter of a rectangle in which a line segment intersects.
p is a point inside the rectangle ($(0, 0)$ is in the center of the rectangle).
$\theta$ is the angle of the of the line segment and it can go from $0$ to $2\pi$.
Thanks in advance.

This is not an analytic solution, but I quickly wrote a computer program as follows. (I thought you might be writing code for this.)
Given the initial point $(x_0, y_0)$ and the direction $\theta$, the solution is immediate if $\theta = 0$, $\pi/2$, $\pi$, or $3\pi/2$. So assume $\theta$ is none of these values and compute the four numbers
$$t_1 = (w/2 - x_0)/\cos\theta$$ $$t_2 = (-w/2 - x_0)/\cos\theta$$ $$t_3 = (h/2 - y_0)/\sin\theta$$ $$t_4 = (-h/2 - y_0)/\sin\theta$$
Let $t^\star$ be the smallest positive value among these. Then the intersection point is $(x_0 + t^\star\cos\theta, y_0+t^\star\sin\theta)$.